package com.ruoyi.develop.goodsSaledo.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

import com.ruoyi.common.core.domain.entity.SysArea;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.IdUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.goodsOrderIn.domain.GoodsOrderIn;
import com.ruoyi.develop.goodsOrderIn.mapper.GoodsOrderInMapper;
import com.ruoyi.develop.goodsOrderMaterials.domain.GoodsOrderMaterials;
import com.ruoyi.develop.goodsOrderMaterials.service.IGoodsOrderMaterialsService;
import com.ruoyi.develop.goodsSale.domain.GoodsSale;
import com.ruoyi.develop.goodsSale.mapper.GoodsSaleMapper;
import com.ruoyi.develop.goodsSaleMaterial.domain.GoodsSaleMaterial;
import com.ruoyi.develop.goodsSaleMaterial.service.IGoodsSaleMaterialService;
import com.ruoyi.develop.goodsSaledoGongxu.domain.GoodsSaledoGongxu;
import com.ruoyi.develop.goodsSaledoGongxu.service.IGoodsSaledoGongxuService;
import com.ruoyi.develop.goodsSupplier.domain.GoodsSupplier;
import com.ruoyi.develop.goodsSupplier.service.IGoodsSupplierService;
import com.ruoyi.develop.lnGongyi.domain.LnGongyi;
import com.ruoyi.develop.lnGongyi.service.ILnGongyiService;
import com.ruoyi.develop.lnGongyigongxu.domain.LnGongyigongxu;
import com.ruoyi.develop.lnGongyigongxu.service.ILnGongyigongxuService;
import com.ruoyi.develop.lnGongyigoods.domain.LnGongyigoods;
import com.ruoyi.develop.lnGongyigoods.service.ILnGongyigoodsService;
import com.ruoyi.develop.lvDo.domain.LvDo;
import com.ruoyi.develop.lvDo.service.ILvDoService;
import com.ruoyi.develop.orderIronRecord.domain.OrderIronRecord;
import com.ruoyi.develop.process.processPleaseBuy.service.IProcessPleaseBuyService;
import com.ruoyi.develop.projectBaseInfo.domain.ProjectBaseInfo;
import com.ruoyi.develop.projectBaseInfo.service.IProjectBaseInfoService;
import com.ruoyi.export.service.impl.ExportServiceImpl;
import com.ruoyi.system.service.ISysAreaService;
import org.apache.poi.ss.usermodel.DateUtil;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.develop.goodsSaledo.mapper.GoodsSaledoMapper;
import com.ruoyi.develop.goodsSaledo.domain.GoodsSaledo;
import com.ruoyi.develop.goodsSaledo.service.IGoodsSaledoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 请购单（自制/采购/外协）Service业务层处理
 *
 * @author qh
 * @date 2024-08-09
 */
@Service
public class GoodsSaledoServiceImpl implements IGoodsSaledoService {
    @Resource
    private GoodsSaledoMapper goodsSaledoMapper;
    @Resource
    private ILvDoService lvDoService;
    @Resource
    private GoodsOrderInMapper goodsOrderInMapper;
    @Autowired
    private ISysAreaService areaService;
    @Resource
    private IProjectBaseInfoService projectBaseInfoService;
    @Resource
    private GoodsSaleMapper goodsSaleMapper;
    @Autowired
    private ExportServiceImpl exportService;
    @Value(value = "${ruoyi.path}")
    public String basePath;
    @Value(value = "${ruoyi.templatePath}")
    public String templatePath;
    @Value(value = "${ruoyi.templateImport}")
    public String templateImport;
    @Autowired
    private IGoodsOrderMaterialsService iGoodsOrderMaterialsService;
    @Autowired
    private IGoodsSaleMaterialService iGoodsSaleMaterialService;
    @Autowired
    private IGoodsSupplierService iGoodsSupplierService;
    @Autowired
    private IGoodsSaledoGongxuService iGoodsSaledoGongxuService;
    @Autowired
    private ILnGongyiService iLnGongyiService;
    @Autowired
    private ILnGongyigoodsService lnGongyigoodsService;
    @Autowired
    private ILnGongyigongxuService iLnGongyigongxuService;

    @Autowired
    private IProcessPleaseBuyService processPleaseBuyService;


    /**
     * 查询请购单（自制/采购/外协）
     *
     * @param id 请购单（自制/采购/外协）主键
     * @return 请购单（自制/采购/外协）
     */
    @Override
    public GoodsSaledo selectById(String id) {
        return goodsSaledoMapper.selectById(id);
    }

    @Override
    public GoodsSaledo listGoodsOrderInById(String id) {
        return goodsSaledoMapper.listGoodsOrderInById(id);
    }

    @Override
    public void subSuccess(String lvDoId) {
        LvDo lvDo = lvDoService.selectById(lvDoId);
        lvDo.setStatus(BusinessConstants.PROJECT_4);
        lvDoService.update(lvDo);
        // 插入流转记录
        processPleaseBuyService.insertPleaseBuyProcess(lvDo.getId(), "", "请购单"+SecurityUtils.getUsername()+"采购审核通过");
        updateStatusByMainId(BusinessConstants.PROJECT_4, lvDoId);
    }

    @Override
    public void subSuccessToCaigou(String lvDoId) {
        LvDo lvDo = lvDoService.selectById(lvDoId);
        lvDo.setStatus(BusinessConstants.PROJECT_6);
        lvDoService.update(lvDo);
        // 插入流转记录
        processPleaseBuyService.insertPleaseBuyProcess(lvDo.getId(), "", "采购部审核通过");

        GoodsSaledo params = new GoodsSaledo();
        params.setMainId(lvDoId);
        params.setIsdo(BusinessConstants.STATUS_NO);
        params.setIsBuy(BusinessConstants.GOODS_IS_BUY_YES);
        List<GoodsSaledo> list = goodsSaledoMapper.selectList(params);
        for (GoodsSaledo goodsSaledo : list) {
            goodsSaledo.setStatus(BusinessConstants.SALE_TYPE_13);
            goodsSaledoMapper.update(goodsSaledo);
        }
    }

    /**
     * 查询请购单（自制/采购/外协）列表
     *
     * @param entity 请购单（自制/采购/外协）
     * @return 请购单（自制/采购/外协）
     */
    @Override
    public List<GoodsSaledo> selectList(GoodsSaledo entity) {
        return goodsSaledoMapper.selectList(entity);
    }

    @Override
    public List<GoodsSaledo> listBuyRemainNotZero(GoodsSaledo entity) {
        return goodsSaledoMapper.listBuyRemainNotZero(entity);
    }


    @Override
    public List<GoodsSaledo> selectListMerge(GoodsSaledo entity) {
        return goodsSaledoMapper.selectListMerge(entity);
    }


    @Override
    public List<GoodsSaledo> listQinggou(GoodsSaledo entity) {
        return goodsSaledoMapper.listQinggou(entity);
    }

    @Override
    public List<GoodsSaledo> listQinggouIsDo(GoodsSaledo entity) {
        return goodsSaledoMapper.listQinggouIsDo(entity);
    }
    @Override
    public List<GoodsSaledo> listQinggouAll(GoodsSaledo entity) {
        return goodsSaledoMapper.listQinggouAll(entity);
    }


    @Override
    public List<GoodsSaledo> listSuoding(GoodsSaledo entity) {
        return goodsSaledoMapper.listSuoding(entity);
    }

    @Override
    public List<GoodsSaledo> listQinggouByBuyallId(GoodsSaledo entity) {
        return goodsSaledoMapper.listQinggouByBuyallId(entity);
    }

    /**
     * 新增请购单（自制/采购/外协）
     *
     * @param entity 请购单（自制/采购/外协）
     * @return 结果
     */
    @Override
    public int insert(GoodsSaledo entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        return goodsSaledoMapper.insert(entity);
    }

    /**
     * 修改请购单（自制/采购/外协）
     *
     * @param entity 请购单（自制/采购/外协）
     * @return 结果
     */
    @Override
    public int update(GoodsSaledo entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        return goodsSaledoMapper.update(entity);
    }

    //技术修改
    public int editAndGoodsSale(GoodsSaledo entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        GoodsSale goodsSale=goodsSaleMapper.selectById(entity.getSaleId());
        if(goodsSale!=null){
            goodsSale.setIsdo(entity.getIsdo());
            goodsSaleMapper.update(goodsSale);
        }
        LvDo lvDo=lvDoService.selectById(entity.getMainId());
        if(lvDo!=null){
            if(BusinessConstants.PLEASE_BUY_STATUS_BUY_DEPT_PASS.equals(lvDo.getStatus())){
                entity.setStatus(BusinessConstants.SALE_TYPE_13);
            }
        }
        return goodsSaledoMapper.update(entity);
    }

    @Override
    public int updateJishu(GoodsSaledo entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        if (StringUtils.isNotBlank(entity.getIsdo())) {
            if (BusinessConstants.GOODS_DO_YES.equals(entity.getIsdo())) {
                entity.setStatus(BusinessConstants.SALE_TYPE_5);
            } else {
                entity.setStatus(BusinessConstants.SALE_TYPE_3);
            }
        }
        return goodsSaledoMapper.update(entity);
    }

    /**
     * 批量删除请购单（自制/采购/外协）
     *
     * @param ids 需要删除的请购单（自制/采购/外协）主键
     * @return 结果
     */
    @Override
    public int deleteByIds(String[] ids) {
        return goodsSaledoMapper.deleteByIds(ids);
    }

    /**
     * 批量删除请购单  订单产品二次请购
     *
     * @param ids 需要删除的请购单（自制/采购/外协）主键
     * @return 结果
     */
    @Override
    public int deleteTwiceBuyGoodsByIds(String[] ids) {
        for (String id : ids) {
            GoodsSaledo goodsSaledo = goodsSaledoMapper.selectById(id);
            GoodsSale goodsSale = goodsSaleMapper.selectById(goodsSaledo.getGoodsSaleId());
            goodsSale.setLockCount(goodsSale.getLockCount().add(goodsSaledo.getPleaseBuyCount()));
            goodsSale.setPleaseBuyCount(goodsSale.getPleaseBuyCount().subtract(goodsSaledo.getPleaseBuyCount()));
            goodsSaleMapper.update(goodsSale);
            GoodsOrderIn goodsOrderIn = goodsOrderInMapper.selectById(goodsSaledo.getGoodsId());
            goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(goodsSaledo.getPleaseBuyCount()));
            goodsOrderInMapper.update(goodsOrderIn);
        }
        return goodsSaledoMapper.deleteByIds(ids);
    }


    @Override
    public int updateStatusByMainId(String status, String mainId) {
        return goodsSaledoMapper.updateStatusByMainId(status, mainId);
    }


    @Override
    public int updateStatusByMainIdCaigou(String status, String mainId) {
        return goodsSaledoMapper.updateStatusByMainIdCaigou(status, mainId);
    }

    @Override
    public int deleteByGoodsSaleId(String id) {
        return goodsSaledoMapper.deleteByGoodsSaleId(id);
    }

    @Override
    public int isNotDo(String id) {
        return goodsSaledoMapper.isNotDo(id);
    }
    @Override
    public int isDo(String id) {
        return goodsSaledoMapper.isDo(id);
    }
    /**
     * 删除请购单（自制/采购/外协）信息
     *
     * @param id 请购单（自制/采购/外协）主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return goodsSaledoMapper.deleteById(id);
    }

    @Override
    @Transactional
    public String insertBatch(GoodsSaledo goodsSaledo) {
        List<GoodsSaledo> rows = goodsSaledo.getColumns();
        // 请购单
        LvDo lvDo = goodsSaledo.getLvDo();
        lvDo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_TECH_SUBMIT);//技术提交
        lvDoService.update(lvDo);
        // 插入流转记录
        processPleaseBuyService.insertPleaseBuyProcess(lvDo.getId(), "", "提交到采购");

        if (!rows.isEmpty()) {
            String errorChaijie = "";
            for (GoodsSaledo entity : rows) {
                if (BusinessConstants.GOODS_DO_YES.equals(entity.getIsdo())) {
                    GoodsOrderIn goodsOrderIn = goodsOrderInMapper.selectById(entity.getGoodsId());
                    if (BusinessConstants.TYPE_CHAIJIE_NO.equals(goodsOrderIn.getIschaijie())) {
                        errorChaijie = goodsOrderIn.getCode() + "," + errorChaijie;
                    }
                }
            }
            if (StringUtils.isNotBlank(errorChaijie)) {
                return "产品编码为：" + errorChaijie + "  产品未拆解，请拆解后重新发请购！";
            }
            for (GoodsSaledo entity : rows) {
                GoodsSale goodsSale = goodsSaleMapper.selectById(entity.getGoodsSaleId());
                // 如果是二次请购 不改变订单状态
                if (!BusinessConstants.PLEASE_BUY_SOURCE_ORDER_TWICE.equals(lvDo.getSource())) {
                    if (goodsSale != null) {
                        goodsSale.setIsdo(entity.getIsdo());
                        if (BusinessConstants.GOODS_DO_YES.equals(entity.getIsdo())) {
                            goodsSale.setStatus(BusinessConstants.GOODS_STATUS_IS_DO_YES);
                        }
                        if (BusinessConstants.GOODS_DO_NO.equals(entity.getIsdo())) {
                            goodsSale.setStatus(BusinessConstants.GOODS_3);
                        }
                        goodsSale.setPleaseBuyCount(entity.getPleaseBuyCount());
                        goodsSaleMapper.update(goodsSale);
                    }

                    if (StringUtils.isNotBlank(entity.getProjectId())) {
                        for (String projectId : entity.getProjectId().split(",")) {
                            if (StringUtils.isNotBlank(projectId)) {
                                ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(projectId);
                                projectBaseInfo.setStatus(BusinessConstants.PROJECT_3);
                                projectBaseInfoService.update(projectBaseInfo);
                            }
                        }
                    }

                }

                goodsSaledo = new GoodsSaledo();
                goodsSaledo.setId(entity.getId());
                goodsSaledo.setType("产品");
                goodsSaledo.setGongchengName(entity.getGongchengName());
                // goodsSaledo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_TECH_SUBMIT);//技术提交
                if (BusinessConstants.GOODS_DO_YES.equals(entity.getIsdo())) {
                    goodsSaledo.setStatus(BusinessConstants.GOODS_STATUS_IS_DO_YES);//自制
                } else {
                    goodsSaledo.setStatus(BusinessConstants.GOODS_3);//和订单产品一致
                }
                goodsSaledo.setGoodsId(entity.getGoodsId());
                goodsSaledo.setGoodsCode(entity.getGoodsCode());
                goodsSaledo.setIsdo(entity.getIsdo());
                goodsSaledo.setGoodModel(entity.getGoodModel());
                goodsSaledo.setGoodsBrand(entity.getGoodsBrand());
                goodsSaledo.setGoodsName(entity.getGoodsName());
                goodsSaledo.setGoodsType(entity.getGoodsType());
                goodsSaledo.setUnit(entity.getUnit());
                goodsSaledo.setGoodsUnitPrice(entity.getGoodsUnitPrice());//销售单价
                goodsSaledo.setLockCount(entity.getLockCount());//销售数量（发货数量）
                goodsSaledo.setGoodsTotalPrice(entity.getLockCount().multiply(entity.getGoodsUnitPrice()));
                goodsSaledo.setOrderCount(entity.getOrderCount());//订单需求量
                goodsSaledo.setPleaseBuyCount(entity.getPleaseBuyCount());//请购数量
                goodsSaledo.setRemark(entity.getRemark());
                goodsSaledo.setMainId(lvDo.getId());
                goodsSaledo.setNos(lvDo.getNos());
                update(goodsSaledo);

            }
        }
        return "";
    }

    @Override
    @Transactional
    public void insertBatchNewToCaigou(GoodsSaledo goodsSaledo, ProjectBaseInfo projectBaseInfo) {
        List<GoodsSaledo> rows = goodsSaledo.getColumns();
        // 如果订单请购下的订单全都有库存，则不生成请购单，直接修改产品状态为发货中，并锁定库存
        boolean allInStock = true;
        for (GoodsSaledo entity : rows) {
            if (entity.getPleaseBuyCount() != null && entity.getPleaseBuyCount().compareTo(new BigDecimal(0)) != 0) {//请购数量 = 0  正数 负数都需要请购
                allInStock = false;
            }
        }
        if (allInStock) {
            for (GoodsSaledo entity : rows) {
                GoodsSale goodsSale = goodsSaleMapper.selectById(entity.getId());
                goodsSale.setLockCount(entity.getLockCount());
                goodsSale.setStatus(BusinessConstants.SALE_TYPE_11);
                // 更新 锁定 数量
                GoodsOrderIn goodsOrderIn = goodsOrderInMapper.selectById(goodsSale.getGoodsId());
                if (goodsOrderIn != null) {
                    goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(entity.getLockCount()));
                    goodsOrderInMapper.update(goodsOrderIn);
                }
                goodsSaleMapper.update(goodsSale);
                //计算订单利润
                if (goodsOrderIn != null && entity.getLockCount().compareTo(BigDecimal.ZERO) > 0 && goodsOrderIn.getCostPrice().compareTo(BigDecimal.ZERO) > 0) {
                    ProjectBaseInfo projectBaseInfo1 = projectBaseInfoService.selectById(goodsSale.getProjectId());
                    projectBaseInfo1.setBuyMoney(projectBaseInfo1.getBuyMoney().add(entity.getLockCount().multiply(goodsOrderIn.getCostPrice())));
                    projectBaseInfo1.setProfitMoney(projectBaseInfo1.getBackMoney().subtract(projectBaseInfo1.getBuyMoney()).subtract(projectBaseInfo1.getFeeMoney()));
                    projectBaseInfoService.updateBackMoney(projectBaseInfo1);
                }
            }
            return;
        }
        //   如果订单请购下的订单部分有库存，则生成请购单，
        // 1 不需要请购的直接修改产品状态为待发货，并锁定库存 ，
        // 2 需要请购的 提交请购
        //生成请购单 销售单号按照天 递增
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String today = sdf.format(new Date());
        String codeMaxString = lvDoService.selectMaxCode(today);
        if (StringUtils.isNotBlank(codeMaxString)) {
            // 最大编号+1
            codeMaxString = Long.parseLong(codeMaxString) + 1 + "";
        } else {
            codeMaxString = today + "0001";
        }
        if (!rows.isEmpty()) {
            // lvDo 请购单
            LvDo lvdo = new LvDo();
            lvdo.setMainId(projectBaseInfo.getId());
            lvdo.setName(projectBaseInfo.getName());
            lvdo.setCode(projectBaseInfo.getCode());
            lvdo.setSource(BusinessConstants.PLEASE_BUY_SOURCE_ORDER);
            lvdo.setNos(codeMaxString);
            lvdo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_TECH_SUBMIT);
            lvdo.setDdDate(DateUtils.getNowDate());
            lvdo.setMoney(projectBaseInfo.getContractMoney());
            lvdo.setSubDate(projectBaseInfo.getDeliveryTime());//需求日期
            lvdo.setCustomerId(projectBaseInfo.getCustomId());
            lvdo.setCustomerName(projectBaseInfo.getCustomName());
            lvdo.setUserId(projectBaseInfo.getSalesmanId());
            lvdo.setUserName(projectBaseInfo.getSalesmanName());
            lvdo.setDeptId(projectBaseInfo.getDeptId());
            lvdo.setDeptName(projectBaseInfo.getDeptName());
            lvDoService.insert(lvdo);

            for (GoodsSaledo entity : rows) {
                GoodsSale goodsSale = goodsSaleMapper.selectById(entity.getId());
                if (goodsSale != null) {
                    //goodsSale.setIsdo(entity.getIsdo());
                    goodsSale.setLvdoId(lvdo.getId());
                    goodsSale.setLvdoNo(lvdo.getNos());
                    goodsSale.setStatus(BusinessConstants.PROJECT_4);
                    if (entity.getLockCount() != null) {
                        goodsSale.setGoodsCount(entity.getLockCount());
                        goodsSale.setLockCount(entity.getLockCount());
                        goodsSale.setPleaseBuyCount(entity.getPleaseBuyCount());
                    } else {
                        goodsSale.setPleaseBuyCount(goodsSale.getOrderCount());
                    }
                    goodsSaleMapper.update(goodsSale);
                }
                GoodsOrderIn goodsOrderIn = goodsOrderInMapper.selectById(goodsSale.getGoodsId());
                if (goodsOrderIn != null) {
                    goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(entity.getLockCount()));
                    goodsOrderInMapper.update(goodsOrderIn);
                }
                goodsSaledo = new GoodsSaledo();
                goodsSaledo.setId(IdUtils.fastSimpleUUID());
                goodsSaledo.setGongchengName(entity.getGongchengName());
                goodsSaledo.setGoodsSaleId(goodsSale.getId());
                goodsSaledo.setType("产品");
                goodsSaledo.setIsdo(entity.getIsdo());
                //goodsSaledo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_TECH_SUBMIT);
                goodsSaledo.setStatus(BusinessConstants.PROJECT_4);//和订单产品保持一致
                goodsSaledo.setGoodsId(entity.getGoodsId());
                goodsSaledo.setGoodsCode(entity.getGoodsCode());
                goodsSaledo.setIsdo(entity.getIsdo());
                goodsSaledo.setGoodModel(entity.getGoodModel());
                goodsSaledo.setGoodsBrand(entity.getGoodsBrand());
                goodsSaledo.setGoodsName(entity.getGoodsName());
                goodsSaledo.setGoodsType(entity.getGoodsType());
                goodsSaledo.setSaleDate(goodsSale.getDeliveryTime());
                goodsSaledo.setUnit(entity.getUnit());
                goodsSaledo.setGoodsUnitPrice(entity.getGoodsUnitPrice());//销售单价
                goodsSaledo.setLockCount(entity.getLockCount());//锁定数量
                goodsSaledo.setGoodsTotalPrice(entity.getLockCount().multiply(entity.getGoodsUnitPrice()));
                goodsSaledo.setOrderCount(entity.getOrderCount());//订单需求量
                goodsSaledo.setPleaseBuyCount(entity.getPleaseBuyCount());//请购数量 = 订单需求量 - 库存锁定数量 也有可能多请购
                goodsSaledo.setBuyRemain(entity.getPleaseBuyCount());//采购剩余量

                if (entity.getPleaseBuyCount().compareTo(new BigDecimal(0)) != 0) {//请购数量 = 0  正数 负数都需要请购
                    goodsSaledo.setIsBuy(BusinessConstants.GOODS_IS_BUY_YES);//需要请购
                } else {
                    goodsSaledo.setIsBuy(BusinessConstants.GOODS_IS_BUY_NO);//不需要请购
                }
                goodsSaledo.setRemark(entity.getRemark());
                goodsSaledo.setProjectId(projectBaseInfo.getId());
                goodsSaledo.setProjectNo(projectBaseInfo.getCode());
                goodsSaledo.setProjectName(projectBaseInfo.getName());
                goodsSaledo.setSalesmanId(projectBaseInfo.getSalesmanId());
                goodsSaledo.setSalesmanName(projectBaseInfo.getSalesmanName());
                goodsSaledo.setCustomerId(projectBaseInfo.getCustomId());
                goodsSaledo.setCustomerName(projectBaseInfo.getCustomName());
                goodsSaledo.setDeptId(projectBaseInfo.getDeptId());
                goodsSaledo.setDeptName(projectBaseInfo.getDeptName());
                goodsSaledo.setMainId(lvdo.getId());
                goodsSaledo.setNos(lvdo.getNos());
                insert(goodsSaledo);
            }
        }
    }


    @Override
    @Transactional
    public void insertBatchNew(GoodsSaledo goodsSaledo, ProjectBaseInfo projectBaseInfo) {
        List<GoodsSaledo> rows = goodsSaledo.getColumns();
        // 如果订单请购下的订单全都有库存，则不生成请购单，直接修改产品状态为发货中，并锁定库存
        boolean allInStock = true;
        for (GoodsSaledo entity : rows) {
            if (entity.getPleaseBuyCount() != null && entity.getPleaseBuyCount().compareTo(new BigDecimal(0)) != 0) {//请购数量 = 0  正数 负数都需要请购
                allInStock = false;
            }
        }
        /*if (allInStock) {
            for (GoodsSaledo entity : rows) {
                GoodsSale goodsSale = goodsSaleMapper.selectById(entity.getId());
                goodsSale.setLockCount(entity.getLockCount());
                goodsSale.setStatus(BusinessConstants.SALE_TYPE_11);

                goodsSaleMapper.update(goodsSale);
            }
            return;
        }*/

        //   如果订单请购下的订单部分有库存，则生成请购单，
        // 1 不需要请购的直接修改产品状态为待发货，并锁定库存 ，
        // 2 需要请购的 提交请购

        //生成请购单 销售单号按照天 递增
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String today = sdf.format(new Date());
        String codeMaxString = lvDoService.selectMaxCode(today);
        if (StringUtils.isNotBlank(codeMaxString)) {
            // 最大编号+1
            codeMaxString = Long.parseLong(codeMaxString) + 1 + "";
        } else {
            codeMaxString = today + "0001";
        }

        if (!rows.isEmpty()) {
            // lvDo 请购单
            LvDo lvdo = new LvDo();
            lvdo.setMainId(projectBaseInfo.getId());
            lvdo.setName(projectBaseInfo.getName());
            lvdo.setCode(projectBaseInfo.getCode());
            lvdo.setSource(BusinessConstants.PLEASE_BUY_SOURCE_ORDER);
            lvdo.setNos(codeMaxString);
            lvdo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_STORE_SUBMIT);
            lvdo.setDdDate(projectBaseInfo.getContractDate());
            lvdo.setMoney(projectBaseInfo.getContractMoney());
            lvdo.setSubDate(projectBaseInfo.getDeliveryTime());//需求日期
            lvdo.setCustomerId(projectBaseInfo.getCustomId());
            lvdo.setCustomerName(projectBaseInfo.getCustomName());
            lvdo.setUserId(projectBaseInfo.getSalesmanId());
            lvdo.setUserName(projectBaseInfo.getSalesmanName());
            lvdo.setDeptId(projectBaseInfo.getDeptId());
            lvdo.setDeptName(projectBaseInfo.getDeptName());
            lvDoService.insert(lvdo);

            for (GoodsSaledo entity : rows) {
                GoodsSale goodsSale = goodsSaleMapper.selectById(entity.getId());
                if (goodsSale != null) {
                    //goodsSale.setIsdo(entity.getIsdo());
                    goodsSale.setLvdoId(lvdo.getId());
                    goodsSale.setLvdoNo(lvdo.getNos());
                    goodsSale.setStatus(BusinessConstants.GOODS_2);
                    if (entity.getLockCount() != null) {
                        goodsSale.setGoodsCount(entity.getLockCount());
                        goodsSale.setLockCount(entity.getLockCount());
                        goodsSale.setPleaseBuyCount(entity.getPleaseBuyCount());
                    } else {
                        goodsSale.setPleaseBuyCount(goodsSale.getOrderCount());
                    }
                    goodsSaleMapper.update(goodsSale);
                    // 更新 锁定 数量
                    GoodsOrderIn goodsOrderIn = goodsOrderInMapper.selectById(goodsSale.getGoodsId());
                    if (goodsOrderIn != null) {
                        goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(entity.getLockCount()));
                        goodsOrderInMapper.update(goodsOrderIn);
                    }
                    //计算订单利润
                    if (goodsOrderIn != null && entity.getLockCount().compareTo(BigDecimal.ZERO) > 0 && goodsOrderIn.getCostPrice().compareTo(BigDecimal.ZERO) > 0) {
                        ProjectBaseInfo projectBaseInfo1 = projectBaseInfoService.selectById(goodsSale.getProjectId());
                        projectBaseInfo1.setBuyMoney(projectBaseInfo1.getBuyMoney().add(entity.getLockCount().multiply(goodsOrderIn.getCostPrice())));
                        projectBaseInfo1.setProfitMoney(projectBaseInfo1.getBackMoney().subtract(projectBaseInfo1.getBuyMoney()).subtract(projectBaseInfo1.getFeeMoney()));
                        projectBaseInfoService.updateBackMoney(projectBaseInfo1);
                    }
                }
                GoodsOrderIn goodsOrderIn = goodsOrderInMapper.selectById(goodsSale.getGoodsId());
                if (goodsOrderIn != null) {
                    goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(entity.getLockCount()));
                    goodsOrderInMapper.update(goodsOrderIn);
                }
                goodsSaledo = new GoodsSaledo();
                goodsSaledo.setId(IdUtils.fastSimpleUUID());
                goodsSaledo.setGongchengName(entity.getGongchengName());
                goodsSaledo.setSaleDate(projectBaseInfo.getDeliveryTime());
                goodsSaledo.setGoodsSaleId(goodsSale.getId());
                goodsSaledo.setType("产品");
                goodsSaledo.setIsdo(entity.getIsdo());
                //goodsSaledo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_STORE_SUBMIT);
                goodsSaledo.setGoodsId(entity.getGoodsId());
                goodsSaledo.setGoodsCode(entity.getGoodsCode());
                goodsSaledo.setIsdo(entity.getIsdo());
                goodsSaledo.setGoodModel(entity.getGoodModel());
                goodsSaledo.setGoodsBrand(entity.getGoodsBrand());
                goodsSaledo.setGoodsName(entity.getGoodsName());
                goodsSaledo.setGoodsType(entity.getGoodsType());
                goodsSaledo.setStatus(BusinessConstants.GOODS_2);
                goodsSaledo.setUnit(entity.getUnit());
                goodsSaledo.setGoodsUnitPrice(entity.getGoodsUnitPrice());//销售单价
                goodsSaledo.setLockCount(entity.getLockCount());//锁定数量
                goodsSaledo.setGoodsTotalPrice(entity.getLockCount().multiply(entity.getGoodsUnitPrice()));
                goodsSaledo.setOrderCount(entity.getOrderCount());//订单需求量
                goodsSaledo.setPleaseBuyCount(entity.getPleaseBuyCount());//请购数量 = 订单需求量 - 库存锁定数量 也有可能多请购
                goodsSaledo.setIdx(entity.getSort() == null ? "0" : entity.getSort() + "");
                goodsSaledo.setBuyRemain(entity.getPleaseBuyCount());//采购剩余量
                if (entity.getPleaseBuyCount().compareTo(new BigDecimal(0)) != 0) {//请购数量 = 0  正数 负数都需要请购
                    goodsSaledo.setIsBuy(BusinessConstants.GOODS_IS_BUY_YES);//需要请购
                } else {
                    goodsSaledo.setIsBuy(BusinessConstants.GOODS_IS_BUY_NO);//不需要请购
                }
                goodsSaledo.setRemark(entity.getRemark());
                goodsSaledo.setProjectId(projectBaseInfo.getId());
                goodsSaledo.setProjectNo(projectBaseInfo.getCode());
                goodsSaledo.setProjectName(projectBaseInfo.getName());
                goodsSaledo.setSalesmanId(projectBaseInfo.getSalesmanId());
                goodsSaledo.setSalesmanName(projectBaseInfo.getSalesmanName());
                goodsSaledo.setCustomerId(projectBaseInfo.getCustomId());
                goodsSaledo.setCustomerName(projectBaseInfo.getCustomName());
                goodsSaledo.setDeptId(projectBaseInfo.getDeptId());
                goodsSaledo.setDeptName(projectBaseInfo.getDeptName());
                goodsSaledo.setMainId(lvdo.getId());
                goodsSaledo.setNos(lvdo.getNos());
                insert(goodsSaledo);
            }
        }
    }


    // 多订单合并 请购
    @Override
    @Transactional
    public void insertForOrderMerge(GoodsSaledo goodsSaledo, List<ProjectBaseInfo> projectBaseInfoList) {
        List<GoodsSaledo> rows = goodsSaledo.getColumns();
        boolean allInStock = true;
        for (GoodsSaledo entity : rows) {
            if (entity.getPleaseBuyCount() != null && entity.getPleaseBuyCount().compareTo(new BigDecimal(0)) != 0) {//请购数量 = 0  正数 负数都需要请购
                allInStock = false;
            }
        }
        if (allInStock) {
            for (GoodsSaledo entity : rows) {
                GoodsSale goodsSale = goodsSaleMapper.selectById(entity.getId());
                goodsSale.setLockCount(entity.getLockCount());
                goodsSale.setStatus(BusinessConstants.SALE_TYPE_6);
                goodsSaleMapper.update(goodsSale);
            }
            return;
        }
        StringBuilder orderCode = new StringBuilder();
        StringBuilder orderId = new StringBuilder();
        for (ProjectBaseInfo projectBaseInfo : projectBaseInfoList) {
            orderCode.append(projectBaseInfo.getCode()).append(",");
            orderId.append(projectBaseInfo.getId()).append(",");
        }
        if (rows.size() > 0) {
            LvDo lvdo = new LvDo();
            lvdo.setSource(BusinessConstants.PLEASE_BUY_SOURCE_ORDER_MERGE);
            lvdo.setCode(orderCode.toString());
            lvdo.setMainId(orderId.toString());
            lvdo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_STORE_SUBMIT);
            lvdo.setCustomerId(projectBaseInfoList.get(0).getCustomId());
            lvdo.setCustomerName(projectBaseInfoList.get(0).getCustomName());
            lvdo.setUserId(projectBaseInfoList.get(0).getSalesmanId());
            lvdo.setUserName(projectBaseInfoList.get(0).getSalesmanName());
            lvdo.setDeptId(projectBaseInfoList.get(0).getDeptId());
            lvdo.setDeptName(projectBaseInfoList.get(0).getDeptName());
            lvDoService.insert(lvdo);
            for (GoodsSaledo entity : rows) {
                GoodsSale goodsSale = goodsSaleMapper.selectById(entity.getId());
                if (goodsSale != null) {
                    //goodsSale.setIsdo(entity.getIsdo());
                    goodsSale.setLvdoId(lvdo.getId());
                    goodsSale.setLvdoNo(lvdo.getNos());
                    goodsSale.setStatus(BusinessConstants.GOODS_2);
                    if (entity.getLockCount() != null) {
                        goodsSale.setGoodsCount(entity.getLockCount());
                        goodsSale.setLockCount(entity.getLockCount());
                        goodsSale.setPleaseBuyCount(entity.getPleaseBuyCount());
                    } else {
                        goodsSale.setPleaseBuyCount(goodsSale.getOrderCount());
                        goodsSale.setLockCount(BigDecimal.ZERO);
                    }
                    goodsSaleMapper.update(goodsSale);
                    // 更新 锁定 数量
                    GoodsOrderIn goodsOrderIn = goodsOrderInMapper.selectById(goodsSale.getGoodsId());
                    if (goodsOrderIn != null) {
                        goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(entity.getLockCount()));
                        goodsOrderInMapper.update(goodsOrderIn);
                    }
                    //计算订单利润
                    if (goodsOrderIn != null && entity.getLockCount().compareTo(BigDecimal.ZERO) > 0 && goodsOrderIn.getCostPrice().compareTo(BigDecimal.ZERO) > 0) {
                        ProjectBaseInfo projectBaseInfo1 = projectBaseInfoService.selectById(goodsSale.getProjectId());
                        projectBaseInfo1.setBuyMoney(projectBaseInfo1.getBuyMoney().add(entity.getLockCount().multiply(goodsOrderIn.getCostPrice())));
                        projectBaseInfo1.setProfitMoney(projectBaseInfo1.getBackMoney().subtract(projectBaseInfo1.getBuyMoney()).subtract(projectBaseInfo1.getFeeMoney()));
                        projectBaseInfoService.updateBackMoney(projectBaseInfo1);
                    }
                }
                ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(entity.getProjectId());
                GoodsOrderIn goodsOrderIn = goodsOrderInMapper.selectById(goodsSale.getGoodsId());
                if (goodsOrderIn != null) {
                    goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(entity.getLockCount()));
                    goodsOrderInMapper.update(goodsOrderIn);
                }
                goodsSaledo = new GoodsSaledo();
                goodsSaledo.setId(IdUtils.fastSimpleUUID());
                goodsSaledo.setGongchengName(entity.getGongchengName());
                goodsSaledo.setSaleDate(projectBaseInfo.getDeliveryTime());
                goodsSaledo.setGoodsSaleId(goodsSale.getId());
                goodsSaledo.setType("产品");
                goodsSaledo.setIsdo(entity.getIsdo());
                goodsSaledo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_STORE_SUBMIT);
                goodsSaledo.setGoodsId(entity.getGoodsId());
                goodsSaledo.setGoodsCode(entity.getGoodsCode());
                goodsSaledo.setIsdo(entity.getIsdo());
                goodsSaledo.setGoodModel(entity.getGoodModel());
                goodsSaledo.setGoodsBrand(entity.getGoodsBrand());
                goodsSaledo.setGoodsName(entity.getGoodsName());
                goodsSaledo.setGoodsType(entity.getGoodsType());
                goodsSaledo.setStatus(BusinessConstants.GOODS_2);
                goodsSaledo.setUnit(entity.getUnit());
                goodsSaledo.setGoodsUnitPrice(entity.getGoodsUnitPrice());//销售单价
                goodsSaledo.setLockCount(entity.getLockCount());//锁定数量
                goodsSaledo.setGoodsTotalPrice(entity.getLockCount().multiply(entity.getGoodsUnitPrice()));
                goodsSaledo.setOrderCount(entity.getOrderCount());//订单需求量
                goodsSaledo.setPleaseBuyCount(entity.getPleaseBuyCount());//请购数量 = 订单需求量 - 库存锁定数量 也有可能多请购
                goodsSaledo.setIdx(entity.getSort() == null ? "0" : entity.getSort() + "");
                goodsSaledo.setBuyRemain(entity.getPleaseBuyCount());//采购剩余量
                if(entity.getPleaseBuyCount()==null){
//                    entity.setPleaseBuyCount(BigDecimal.ZERO);
                }
                if (entity.getPleaseBuyCount().compareTo(new BigDecimal(0)) != 0) {//请购数量 = 0  正数 负数都需要请购
                    goodsSaledo.setIsBuy(BusinessConstants.GOODS_IS_BUY_YES);//需要请购
                } else {
                    goodsSaledo.setIsBuy(BusinessConstants.GOODS_IS_BUY_NO);//不需要请购
                }
                goodsSaledo.setRemark(entity.getRemark());
                goodsSaledo.setProjectId(projectBaseInfo.getId());
                goodsSaledo.setProjectNo(projectBaseInfo.getCode());
                goodsSaledo.setProjectName(projectBaseInfo.getName());
                goodsSaledo.setSalesmanId(projectBaseInfo.getSalesmanId());
                goodsSaledo.setSalesmanName(projectBaseInfo.getSalesmanName());
                goodsSaledo.setCustomerId(projectBaseInfo.getCustomId());
                goodsSaledo.setCustomerName(projectBaseInfo.getCustomName());
                goodsSaledo.setDeptId(projectBaseInfo.getDeptId());
                goodsSaledo.setDeptName(projectBaseInfo.getDeptName());
                goodsSaledo.setMainId(lvdo.getId());
                goodsSaledo.setNos(lvdo.getNos());
                insert(goodsSaledo);
            }
        }
    }


    // 多订单合并 请购 库管直接到采购
    @Override
    public void insertForOrderMergeToCaigou(GoodsSaledo goodsSaledo, List<ProjectBaseInfo> projectBaseInfoList) {
        List<GoodsSaledo> rows = goodsSaledo.getColumns();
        boolean allInStock = true;
        for (GoodsSaledo entity : rows) {
            if (entity.getPleaseBuyCount() != null && entity.getPleaseBuyCount().compareTo(new BigDecimal(0)) != 0) {//请购数量 = 0  正数 负数都需要请购
                allInStock = false;
            }
        }
        if (allInStock) {
            for (GoodsSaledo entity : rows) {
                GoodsSale goodsSale = goodsSaleMapper.selectById(entity.getId());
                goodsSale.setLockCount(entity.getLockCount());
                goodsSale.setStatus(BusinessConstants.SALE_TYPE_6);
                goodsSaleMapper.update(goodsSale);
            }
            return;
        }

        StringBuilder orderCode = new StringBuilder();
        StringBuilder orderId = new StringBuilder();
        for (ProjectBaseInfo projectBaseInfo : projectBaseInfoList) {
            orderCode.append(projectBaseInfo.getCode()).append(",");
            orderId.append(projectBaseInfo.getId()).append(",");
        }

        if (rows.size() > 0) {

            LvDo lvdo = new LvDo();
            lvdo.setSource(BusinessConstants.PLEASE_BUY_SOURCE_ORDER_MERGE);
            lvdo.setCode(orderCode.toString());
            lvdo.setMainId(orderId.toString());
            lvdo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_TECH_SUBMIT);
            lvdo.setCustomerId(projectBaseInfoList.get(0).getCustomId());
            lvdo.setCustomerName(projectBaseInfoList.get(0).getCustomName());
            lvdo.setUserId(projectBaseInfoList.get(0).getSalesmanId());
            lvdo.setUserName(projectBaseInfoList.get(0).getSalesmanName());
            lvdo.setDeptId(projectBaseInfoList.get(0).getDeptId());
            lvdo.setDeptName(projectBaseInfoList.get(0).getDeptName());
            lvDoService.insert(lvdo);


            for (GoodsSaledo entity : rows) {
                GoodsSale goodsSale = goodsSaleMapper.selectById(entity.getId());
                if (goodsSale != null) {
                    //goodsSale.setIsdo(entity.getIsdo());
                    goodsSale.setLvdoId(lvdo.getId());
                    goodsSale.setLvdoNo(lvdo.getNos());
                    goodsSale.setStatus(BusinessConstants.PROJECT_4);
                    if (entity.getLockCount() != null) {
                        goodsSale.setGoodsCount(entity.getLockCount());
                        goodsSale.setLockCount(entity.getLockCount());
                        goodsSale.setPleaseBuyCount(entity.getPleaseBuyCount());
                    } else {
                        goodsSale.setPleaseBuyCount(goodsSale.getOrderCount());
                    }
                    goodsSaleMapper.update(goodsSale);
                    // 更新 锁定 数量
                    GoodsOrderIn goodsOrderIn = goodsOrderInMapper.selectById(goodsSale.getGoodsId());
                    if (goodsOrderIn != null) {
                        goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(entity.getLockCount()));
                        goodsOrderInMapper.update(goodsOrderIn);
                    }
                    //计算订单利润
                    if (goodsOrderIn != null && entity.getLockCount().compareTo(BigDecimal.ZERO) > 0 && goodsOrderIn.getCostPrice().compareTo(BigDecimal.ZERO) > 0) {
                        ProjectBaseInfo projectBaseInfo1 = projectBaseInfoService.selectById(goodsSale.getProjectId());
                        projectBaseInfo1.setBuyMoney(projectBaseInfo1.getBuyMoney().add(entity.getLockCount().multiply(goodsOrderIn.getCostPrice())));
                        projectBaseInfo1.setProfitMoney(projectBaseInfo1.getBackMoney().subtract(projectBaseInfo1.getBuyMoney()).subtract(projectBaseInfo1.getFeeMoney()));
                        projectBaseInfoService.updateBackMoney(projectBaseInfo1);
                    }
                }
                ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(entity.getProjectId());
                GoodsOrderIn goodsOrderIn = goodsOrderInMapper.selectById(goodsSale.getGoodsId());
                if (goodsOrderIn != null) {
                    goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(entity.getLockCount()));
                    goodsOrderInMapper.update(goodsOrderIn);
                }
                goodsSaledo = new GoodsSaledo();
                goodsSaledo.setId(IdUtils.fastSimpleUUID());
                goodsSaledo.setGongchengName(entity.getGongchengName());
                goodsSaledo.setSaleDate(projectBaseInfo.getDeliveryTime());
                goodsSaledo.setGoodsSaleId(goodsSale.getId());
                goodsSaledo.setType("产品");
                goodsSaledo.setIsdo(entity.getIsdo());
                goodsSaledo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_TECH_SUBMIT);
                goodsSaledo.setGoodsId(entity.getGoodsId());
                goodsSaledo.setGoodsCode(entity.getGoodsCode());
                goodsSaledo.setIsdo(entity.getIsdo());
                goodsSaledo.setGoodModel(entity.getGoodModel());
                goodsSaledo.setGoodsBrand(entity.getGoodsBrand());
                goodsSaledo.setGoodsName(entity.getGoodsName());
                goodsSaledo.setGoodsType(entity.getGoodsType());
                goodsSaledo.setStatus(BusinessConstants.PROJECT_4);
                goodsSaledo.setUnit(entity.getUnit());
                goodsSaledo.setGoodsUnitPrice(entity.getGoodsUnitPrice());//销售单价
                goodsSaledo.setLockCount(entity.getLockCount());//锁定数量
                goodsSaledo.setGoodsTotalPrice(entity.getLockCount().multiply(entity.getGoodsUnitPrice()));
                goodsSaledo.setOrderCount(entity.getOrderCount());//订单需求量
                goodsSaledo.setPleaseBuyCount(entity.getPleaseBuyCount());//请购数量 = 订单需求量 - 库存锁定数量 也有可能多请购
                goodsSaledo.setBuyRemain(entity.getPleaseBuyCount());//采购剩余量
                goodsSaledo.setIdx(entity.getSort() == null ? "0" : entity.getSort() + "");

                if (entity.getPleaseBuyCount().compareTo(new BigDecimal(0)) != 0) {//请购数量 = 0  正数 负数都需要请购
                    goodsSaledo.setIsBuy(BusinessConstants.GOODS_IS_BUY_YES);//需要请购
                } else {
                    goodsSaledo.setIsBuy(BusinessConstants.GOODS_IS_BUY_NO);//不需要请购
                }
                goodsSaledo.setRemark(entity.getRemark());
                goodsSaledo.setProjectId(projectBaseInfo.getId());
                goodsSaledo.setProjectNo(projectBaseInfo.getCode());
                goodsSaledo.setProjectName(projectBaseInfo.getName());
                goodsSaledo.setSalesmanId(projectBaseInfo.getSalesmanId());
                goodsSaledo.setSalesmanName(projectBaseInfo.getSalesmanName());
                goodsSaledo.setCustomerId(projectBaseInfo.getCustomId());
                goodsSaledo.setCustomerName(projectBaseInfo.getCustomName());
                goodsSaledo.setDeptId(projectBaseInfo.getDeptId());
                goodsSaledo.setDeptName(projectBaseInfo.getDeptName());
                goodsSaledo.setMainId(lvdo.getId());
                goodsSaledo.setNos(lvdo.getNos());

                insert(goodsSaledo);
            }
        }
    }


    //其他产品提交请购
    @Override
    @Transactional
    public void submitScalado(GoodsSaledo goodsSaledo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = sdf.format(new Date());
        List<GoodsSaledo> rows = goodsSaledo.getColumns();
        ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(goodsSaledo.getProjectId());

        LvDo lvdo = new LvDo();
        lvdo.setMainId(projectBaseInfo.getId());
        lvdo.setName(projectBaseInfo.getName());
        lvdo.setCode(projectBaseInfo.getCode());
        lvdo.setNos(time);
        lvdo.setStatus("22");//请购中
        lvdo.setDdDate(projectBaseInfo.getContractDate());
        lvdo.setMoney(projectBaseInfo.getContractMoney());
//        lvdo.setSubDate();//需求日期
        lvdo.setCustomerId(projectBaseInfo.getCustomId());
        lvdo.setCustomerName(projectBaseInfo.getCustomName());
        lvdo.setDeptId(projectBaseInfo.getDeptId());
        lvdo.setDeptName(projectBaseInfo.getDeptName());
        lvDoService.insert(lvdo);
        if (rows.size() > 0) {
            for (GoodsSaledo entity : rows) {
                entity.setType("其他");
                entity.setStatus("22");//请购中
                entity.setMainId(lvdo.getId());
                entity.setNos(lvdo.getNos());
                if (StringUtils.isNotBlank(entity.getId())) {
                    update(entity);
                } else {
                    insert(entity);
                }

            }
        }
    }

    //更新驳回的产品提交请购
    @Override
    @Transactional
    public void updateLvdo(LvDo lvDo) {
        List<GoodsOrderIn> rows = lvDo.getColumns();
        ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo();
        if (StringUtils.isNotBlank(lvDo.getMainId())) {
            projectBaseInfo = projectBaseInfoService.selectById(lvDo.getMainId());
        }
        lvDo.setNos(lvDo.getNos());
        if (StringUtils.isNotBlank(projectBaseInfo.getId())) {
            lvDo.setCode(projectBaseInfo.getCode());
            lvDo.setName(projectBaseInfo.getName());
            lvDo.setMainId(projectBaseInfo.getId());
        } else {
            lvDo.setCode("");
            lvDo.setName("");
            lvDo.setMainId("");
        }
        lvDo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_TECH_SUBMIT);
        lvDo.setDdDate(lvDo.getDdDate());//下单日期
        lvDo.setSubDate(lvDo.getSubDate());//需求日期
        lvDo.setCustomerId(lvDo.getCustomerId());
        lvDo.setCustomerName(lvDo.getCustomerName());
        lvDo.setUserId(lvDo.getUserId());
        lvDo.setUserName(lvDo.getUserName());
        lvDo.setDeptId(lvDo.getDeptId());
        lvDo.setDeptName(lvDo.getDeptName());
        lvDo.setYwType(lvDo.getYwType());
        lvDo.setType(lvDo.getType());
        lvDo.setRemark(lvDo.getRemark());
        lvDoService.update(lvDo);
        if (!rows.isEmpty()) {
            for (GoodsOrderIn entity : rows) {
                GoodsSaledo goodsSaledo = goodsSaledoMapper.selectById(entity.getId());
                if (goodsSaledo != null) {
                    goodsSaledo.setProjectId(lvDo.getMainId());
                    goodsSaledo.setProjectNo(lvDo.getCode());
                    goodsSaledo.setProjectName(lvDo.getName());
                    goodsSaledo.setSalesmanId(lvDo.getUserId());
                    goodsSaledo.setSalesmanName(lvDo.getUserName());
                    goodsSaledo.setCustomerId(lvDo.getCustomerId());
                    goodsSaledo.setCustomerName(lvDo.getCustomerName());
                    goodsSaledo.setDeptId(lvDo.getDeptId());
                    goodsSaledo.setDeptName(lvDo.getDeptName());
                    goodsSaledo.setMainId(lvDo.getId());
                    goodsSaledo.setNos(lvDo.getNos());
                    goodsSaledo.setSaleDate(lvDo.getSubDate());//需求日期
                    if (BusinessConstants.GOODS_DO_YES.equals(goodsSaledo.getIsdo())) {
                        goodsSaledo.setStatus(BusinessConstants.GOODS_STATUS_IS_DO_YES);
                    } else {
                        goodsSaledo.setStatus(BusinessConstants.GOODS_3);
                    }
                    update(goodsSaledo);
                }
            }
        }
    }

    //其他产品修改请购
    @Override
    @Transactional
    public void insertDoByLvdo(GoodsSaledo goodsSaledoOld) {
        List<GoodsOrderIn> rows = goodsSaledoOld.getColumnsDo();
        if (!rows.isEmpty()) {
            for (GoodsOrderIn entity : rows) {
                GoodsSaledo goodsSaledo = new GoodsSaledo();
                goodsSaledo.setId(IdUtils.fastSimpleUUID());
                if (StringUtils.isNoneBlank(goodsSaledoOld.getMainId())) {
                    goodsSaledo.setMainId(goodsSaledoOld.getMainId());
                }
                goodsSaledo.setType("其他");
                goodsSaledo.setStatus(BusinessConstants.PROJECT_3);//驳回请购
                //goodsSaledo.setStatus(BusinessConstants.PROJECT_3);//已请购
                goodsSaledo.setGoodsId(entity.getId());
                goodsSaledo.setGoodsCode(entity.getCode());
                goodsSaledo.setGoodModel(entity.getModel());
                goodsSaledo.setGoodsBrand(entity.getBrand());
                goodsSaledo.setGoodsName(entity.getName());
                goodsSaledo.setUnit(entity.getUnit());
                goodsSaledo.setGoodsType(entity.getGoodsType());
                //goodsSaledo.setGoodsUnitPrice(entity.getGoodsUnitPrice());//销售单价
                //goodsSaledo.setGoodsCount(entity.getGoodsCount());//销售数量（发货数量）
                //goodsSaledo.setGoodsTotalPrice(entity.getGoodsCount().multiply(entity.getGoodsUnitPrice()));
                goodsSaledo.setOrderCount(entity.getCounts());//订单需求量
                goodsSaledo.setPleaseBuyCount(entity.getCounts());//请购数量
                goodsSaledo.setBuyRemain(entity.getCounts());//采购剩余量
                goodsSaledo.setRemark(entity.getRemark());
                insert(goodsSaledo);
            }
        }
    }

    //其他产品驳回请购
    @Override
    @Transactional
    public void insertDoByLvdoBohui(GoodsSaledo goodsSaledoOld) {
        List<GoodsOrderIn> rows = goodsSaledoOld.getColumnsDo();
        if (!rows.isEmpty()) {
            for (GoodsOrderIn entity : rows) {
                GoodsSaledo goodsSaledo = new GoodsSaledo();
                goodsSaledo.setId(IdUtils.fastSimpleUUID());
                if (StringUtils.isNoneBlank(goodsSaledoOld.getMainId())) {
                    goodsSaledo.setMainId(goodsSaledoOld.getMainId());
                }
                goodsSaledo.setType("其他");
                goodsSaledo.setStatus(BusinessConstants.PROJECT_33);//驳回请购
                //goodsSaledo.setStatus(BusinessConstants.PROJECT_3);//已请购
                goodsSaledo.setGoodsId(entity.getId());
                goodsSaledo.setGoodsCode(entity.getCode());
                goodsSaledo.setGoodModel(entity.getModel());
                goodsSaledo.setGoodsBrand(entity.getBrand());
                goodsSaledo.setGoodsName(entity.getName());
                goodsSaledo.setUnit(entity.getUnit());
                goodsSaledo.setGoodsType(entity.getGoodsType());
                goodsSaledo.setIsBuy(BusinessConstants.GOODS_IS_BUY_YES);
                goodsSaledo.setSource(goodsSaledoOld.getSource());
                //goodsSaledo.setGoodsUnitPrice(entity.getGoodsUnitPrice());//销售单价
                //goodsSaledo.setGoodsCount(entity.getGoodsCount());//销售数量（发货数量）
                //goodsSaledo.setGoodsTotalPrice(entity.getGoodsCount().multiply(entity.getGoodsUnitPrice()));
                goodsSaledo.setOrderCount(entity.getCounts());//订单需求量
                goodsSaledo.setPleaseBuyCount(entity.getCounts());//请购数量
                goodsSaledo.setBuyRemain(entity.getCounts());//
                goodsSaledo.setRemark(entity.getRemark());
                insert(goodsSaledo);
            }
        }
    }

    @Override
    public List<GoodsSaledo> listByProjectId(GoodsSaledo entity) {
        return goodsSaledoMapper.listByProjectId(entity);
    }

    //其他产品新增请购记录
    @Override
    @Transactional
    public void insertBatchDo(GoodsSaledo goodsSaledo) {
        List<GoodsOrderIn> rows = goodsSaledo.getColumnsDo();
        if (!rows.isEmpty()) {
            for (GoodsOrderIn entity : rows) {
                goodsSaledo = new GoodsSaledo();
                goodsSaledo.setId(IdUtils.fastSimpleUUID());
                goodsSaledo.setType("其他");
                goodsSaledo.setIsBuy("1");
                goodsSaledo.setStatus(BusinessConstants.PROJECT_2);//请购中
                goodsSaledo.setGoodsId(entity.getId());
                goodsSaledo.setGoodsCode(entity.getCode());
                goodsSaledo.setGoodModel(entity.getModel());
                goodsSaledo.setGoodsBrand(entity.getBrand());
                goodsSaledo.setGoodsName(entity.getName());
                goodsSaledo.setUnit(entity.getUnit());
                goodsSaledo.setGoodsType(entity.getGoodsType());
                //goodsSaledo.setGoodsUnitPrice(entity.getGoodsUnitPrice());//销售单价
                //goodsSaledo.setGoodsCount(entity.getGoodsCount());//销售数量（发货数量）
                //goodsSaledo.setGoodsTotalPrice(entity.getGoodsCount().multiply(entity.getGoodsUnitPrice()));
                goodsSaledo.setOrderCount(entity.getCounts());//订单需求量
                goodsSaledo.setPleaseBuyCount(entity.getCounts());//请购数量
                goodsSaledo.setBuyRemain(entity.getCounts());//采购剩余数量
                goodsSaledo.setRemark(entity.getRemark());
                insert(goodsSaledo);
            }
        }
    }

    //其他产品新增请购记录   ？？？？？？
    @Override
    @Transactional
    public void insertFromGoodsSale(GoodsSaledo goodsSaledo) {
        List<GoodsSale> rows = goodsSaledo.getGoodsSaleList();
        if (!rows.isEmpty()) {
            for (GoodsSale entity : rows) {
                goodsSaledo = new GoodsSaledo();
                goodsSaledo.setId(IdUtils.fastSimpleUUID());
                goodsSaledo.setType("订单二次请购");
                goodsSaledo.setIsBuy("1");
                goodsSaledo.setStatus(BusinessConstants.PROJECT_2);//请购中
                goodsSaledo.setGoodsId(entity.getGoodsId());
                goodsSaledo.setGoodsCode(entity.getGoodsCode());
                goodsSaledo.setGoodModel(entity.getGoodModel());
                goodsSaledo.setGoodsBrand(entity.getGoodsBrand());
                goodsSaledo.setGoodsName(entity.getGoodsName());
                goodsSaledo.setUnit(entity.getUnit());
                goodsSaledo.setGoodsType(entity.getGoodsType());
                goodsSaledo.setOrderCount(entity.getOrderCount());//订单需求量
                goodsSaledo.setPleaseBuyCount(entity.getPleaseBuyCountTmpl());//请购数量
                goodsSaledo.setBuyRemain(entity.getPleaseBuyCountTmpl());//采购剩余数量
                goodsSaledo.setRemark(entity.getRemark());
                goodsSaledo.setGoodsSaleId(entity.getId());
                goodsSaledo.setProjectId(entity.getProjectId());
                goodsSaledo.setProjectNo(entity.getProjectNo());
                goodsSaledo.setGongchengName(entity.getGongchengName());
                goodsSaledo.setCustomerId(entity.getCustomerId());
                goodsSaledo.setCustomerName(entity.getCustomerName());
                insert(goodsSaledo);

                // 更新库存
                GoodsOrderIn goodsOrderIn = goodsOrderInMapper.selectById(entity.getGoodsId());
                if (BusinessConstants.GOODS_31.equals(entity.getStatus())) {
                    goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().subtract(entity.getOrderCount()).add(entity.getPleaseBuyCount()));
                } else {
                    goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().add(entity.getPleaseBuyCount()));
                }
                goodsOrderInMapper.update(goodsOrderIn);
                if (BusinessConstants.GOODS_31.equals(entity.getStatus())) {
                    if(entity.getPleaseBuyCountTmpl().add(entity.getLockCount()).compareTo(entity.getOrderCount()) == 0){
                        entity.setLockCount(entity.getLockCount());
                        entity.setPleaseBuyCount(entity.getPleaseBuyCountTmpl());
                    }else{
                        entity.setLockCount(entity.getLockCount().subtract(entity.getPleaseBuyCountTmpl()));
                        entity.setPleaseBuyCount(entity.getPleaseBuyCount().add(entity.getPleaseBuyCountTmpl()));
                    }
                } else {
                    entity.setLockCount(entity.getLockCount().subtract(entity.getPleaseBuyCountTmpl()));
                    entity.setPleaseBuyCount(entity.getPleaseBuyCount().add(entity.getPleaseBuyCountTmpl()));
                }
                goodsSaleMapper.update(entity);
            }
        }
    }


    //其他产品请购提交请购单（暂存请购单）
    @Override
    @Transactional
    public void insertBatchLvDo(LvDo lvDo) {
        List<GoodsOrderIn> rows = lvDo.getColumns();
        ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo();
        if (StringUtils.isNotBlank(lvDo.getMainId())) {
            projectBaseInfo = projectBaseInfoService.selectById(lvDo.getMainId());
        }
        LvDo lvdo = new LvDo();
        if (StringUtils.isNotBlank(projectBaseInfo.getId())) {
            lvdo.setCode(projectBaseInfo.getCode());
            lvdo.setName(projectBaseInfo.getName());
            lvdo.setMainId(projectBaseInfo.getId());
        }
        lvdo.setSource(BusinessConstants.PLEASE_BUY_SOURCE_OTHER);
        //lvdo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_TECH_SUBMIT);//修改为技术提交状态
        lvdo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_QINGGOU_9);//修改为暂存请购单
        lvdo.setDdDate(lvDo.getDdDate());
        lvdo.setSubDate(lvDo.getSubDate());
        lvdo.setCustomerId(lvDo.getCustomerId());
        lvdo.setCustomerName(lvDo.getCustomerName());
        lvdo.setUserId(lvDo.getUserId());
        lvdo.setUserName(lvDo.getUserName());
        lvdo.setDeptId(lvDo.getDeptId());
        lvdo.setDeptName(lvDo.getDeptName());
        lvdo.setYwType(lvDo.getYwType());
        lvdo.setType(lvDo.getType());
        lvdo.setRemark(lvDo.getRemark());
        lvDoService.insert(lvdo);
        if (!rows.isEmpty()) {
            for (GoodsOrderIn entity : rows) {
                GoodsSaledo goodsSaledo = goodsSaledoMapper.selectById(entity.getId());

                if (goodsSaledo != null) {
                    goodsSaledo.setProjectId(lvdo.getMainId());
                    goodsSaledo.setProjectNo(lvdo.getCode());
                    goodsSaledo.setProjectName(lvdo.getName());
                    goodsSaledo.setSalesmanId(lvdo.getUserId());
                    goodsSaledo.setSalesmanName(lvdo.getUserName());
                    goodsSaledo.setCustomerId(lvdo.getCustomerId());
                    goodsSaledo.setCustomerName(lvdo.getCustomerName());
                    goodsSaledo.setDeptId(lvdo.getDeptId());
                    goodsSaledo.setDeptName(lvdo.getDeptName());
                    goodsSaledo.setMainId(lvdo.getId());
                    goodsSaledo.setSaleDate(lvdo.getSubDate());
                    goodsSaledo.setNos(lvdo.getNos());
                    goodsSaledo.setStatus(BusinessConstants.GOODS_3);
                    update(goodsSaledo);
                }
            }
        }
    }

    //其他产品请购提交请购单（直接提交懂啊采购部门）
    @Override
    @Transactional
    public void submitLvdoToCg(LvDo lvDo) {
        List<GoodsOrderIn> rows = lvDo.getColumns();
        ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo();
        if (StringUtils.isNotBlank(lvDo.getMainId())) {
            projectBaseInfo = projectBaseInfoService.selectById(lvDo.getMainId());
        }
        LvDo lvdo = new LvDo();
        if (StringUtils.isNotBlank(projectBaseInfo.getId())) {
            lvdo.setCode(projectBaseInfo.getCode());
            lvdo.setName(projectBaseInfo.getName());
            lvdo.setMainId(projectBaseInfo.getId());
        }
        lvdo.setSource(BusinessConstants.PLEASE_BUY_SOURCE_OTHER);
        lvdo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_TECH_SUBMIT);//修改为技术提交状态（直接提交懂啊采购部门）
        lvdo.setDdDate(lvDo.getDdDate());
        lvdo.setSubDate(lvDo.getSubDate());
        lvdo.setCustomerId(lvDo.getCustomerId());
        lvdo.setCustomerName(lvDo.getCustomerName());
        lvdo.setUserId(lvDo.getUserId());
        lvdo.setUserName(lvDo.getUserName());
        lvdo.setDeptId(lvDo.getDeptId());
        lvdo.setDeptName(lvDo.getDeptName());
        lvdo.setYwType(lvDo.getYwType());
        lvdo.setType(lvDo.getType());
        lvdo.setRemark(lvDo.getRemark());
        lvDoService.insert(lvdo);
        if (!rows.isEmpty()) {
            for (GoodsOrderIn entity : rows) {
                GoodsSaledo goodsSaledo = goodsSaledoMapper.selectById(entity.getId());

                if (goodsSaledo != null) {
                    goodsSaledo.setProjectId(lvdo.getMainId());
                    goodsSaledo.setProjectNo(lvdo.getCode());
                    goodsSaledo.setProjectName(lvdo.getName());
                    goodsSaledo.setSalesmanId(lvdo.getUserId());
                    goodsSaledo.setSalesmanName(lvdo.getUserName());
                    goodsSaledo.setCustomerId(lvdo.getCustomerId());
                    goodsSaledo.setCustomerName(lvdo.getCustomerName());
                    goodsSaledo.setDeptId(lvdo.getDeptId());
                    goodsSaledo.setDeptName(lvdo.getDeptName());
                    goodsSaledo.setMainId(lvdo.getId());
                    goodsSaledo.setNos(lvdo.getNos());
                    goodsSaledo.setSaleDate(lvDo.getSubDate());//需求日期
                    goodsSaledo.setStatus(BusinessConstants.GOODS_3);
                    goodsSaledo.setSource(BusinessConstants.SOURCE_1);
                    update(goodsSaledo);
                }
                /*entity.setRemainderCount(entity.getRemainderCount().subtract(entity.getGoodsCount())) ;
                entity.setShengyu(entity.getRemainderCount().multiply(entity.getCostPriceTax()));
                entity.setBuyDate(null);
                goodsOrderInMapper.update(entity);
*/
            }
        }
    }

    @Override
    @Transactional
    public void submitLvdoToTech(LvDo lvDo) {
        List<GoodsOrderIn> rows = lvDo.getColumns();
        ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo();
        if (StringUtils.isNotBlank(lvDo.getMainId())) {
            projectBaseInfo = projectBaseInfoService.selectById(lvDo.getMainId());
        }
        LvDo lvdo = new LvDo();
        if (StringUtils.isNotBlank(projectBaseInfo.getId())) {
            lvdo.setCode(projectBaseInfo.getCode());
            lvdo.setName(projectBaseInfo.getName());
            lvdo.setMainId(projectBaseInfo.getId());
        }
        lvdo.setSource(BusinessConstants.PLEASE_BUY_SOURCE_OTHER);
        lvdo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_STORE_SUBMIT);//修改为技术提交状态  技术待审核
        lvdo.setDdDate(lvDo.getDdDate());
        lvdo.setSubDate(lvDo.getSubDate());
        lvdo.setCustomerId(lvDo.getCustomerId());
        lvdo.setCustomerName(lvDo.getCustomerName());
        lvdo.setUserId(lvDo.getUserId());
        lvdo.setUserName(lvDo.getUserName());
        lvdo.setDeptId(lvDo.getDeptId());
        lvdo.setDeptName(lvDo.getDeptName());
        lvdo.setYwType(lvDo.getYwType());
        lvdo.setType(lvDo.getType());
        lvdo.setRemark(lvDo.getRemark());
        lvDoService.insert(lvdo);

        processPleaseBuyService.insertPleaseBuyProcess(lvdo.getId(), "", "请购单创建");
        processPleaseBuyService.insertPleaseBuyProcess(lvdo.getId(), "", "提交到技术");

        if (!rows.isEmpty()) {
            for (GoodsOrderIn entity : rows) {
                GoodsSaledo goodsSaledo = goodsSaledoMapper.selectById(entity.getId());
                if (goodsSaledo != null) {
                    goodsSaledo.setProjectId(lvdo.getMainId());
                    goodsSaledo.setProjectNo(lvdo.getCode());
                    goodsSaledo.setProjectName(lvdo.getName());
                    goodsSaledo.setSalesmanId(lvdo.getUserId());
                    goodsSaledo.setSalesmanName(lvdo.getUserName());
                    goodsSaledo.setCustomerId(lvdo.getCustomerId());
                    goodsSaledo.setCustomerName(lvdo.getCustomerName());
                    goodsSaledo.setDeptId(lvdo.getDeptId());
                    goodsSaledo.setDeptName(lvdo.getDeptName());
                    goodsSaledo.setMainId(lvdo.getId());
                    goodsSaledo.setNos(lvdo.getNos());
                    goodsSaledo.setSaleDate(lvDo.getSubDate());//需求日期
                    goodsSaledo.setStatus(BusinessConstants.GOODS_3);
                    goodsSaledo.setSource(BusinessConstants.SOURCE_1);
                    update(goodsSaledo);
                }
            }
        }
    }


    @Override
    @Transactional
    public void submitLvdoToBuyDept(LvDo lvDo) {
        List<GoodsSaledo> rows = lvDo.getGoodsSaledoList();
        ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo();
        if (StringUtils.isNotBlank(lvDo.getMainId())) {
            projectBaseInfo = projectBaseInfoService.selectById(lvDo.getMainId());
        }
        if (StringUtils.isNotBlank(projectBaseInfo.getId())) {
            lvDo.setCode(projectBaseInfo.getCode());
            lvDo.setName(projectBaseInfo.getName());
            lvDo.setMainId(projectBaseInfo.getId());
        }
        lvDo.setSource(BusinessConstants.PLEASE_BUY_SOURCE_OTHER);
        lvDo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_BUY_PASS);//修改为技术提交状态  技术待审核
        lvDoService.insert(lvDo);

        processPleaseBuyService.insertPleaseBuyProcess(lvDo.getId(), "", "请购单创建");
        // sleep 0.1s
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        processPleaseBuyService.insertPleaseBuyProcess(lvDo.getId(), "", "提交到采购部");

        if (!rows.isEmpty()) {
            for (GoodsSaledo entity : rows) {
                entity.setProjectId(lvDo.getMainId());
                entity.setProjectNo(lvDo.getCode());
                entity.setProjectName(lvDo.getName());
                entity.setSalesmanId(lvDo.getUserId());
                entity.setSalesmanName(lvDo.getUserName());
                entity.setCustomerId(lvDo.getCustomerId());
                entity.setCustomerName(lvDo.getCustomerName());
                entity.setDeptId(lvDo.getDeptId());
                entity.setDeptName(lvDo.getDeptName());
                entity.setMainId(lvDo.getId());
                entity.setNos(lvDo.getNos());
                entity.setSaleDate(lvDo.getSubDate());//需求日期
                entity.setStatus(BusinessConstants.PROJECT_4);
                entity.setSource(BusinessConstants.SOURCE_1);
                update(entity);
            }
        }
    }




    @Override
    public void pleaseBuyForMaterial(GoodsSaledo goodsSaledo, OrderIronRecord orderIronRecord) {
        ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(orderIronRecord.getOrderId());
        ;
        List<GoodsSaledo> rows = goodsSaledo.getColumns();
        // 如果订单请购下的订单全都有库存，则不生成请购单，直接修改产品状态为发货中，并锁定库存
        //   如果订单请购下的订单部分有库存，则生成请购单，
        // 1 不需要请购的直接修改产品状态为待发货，并锁定库存 ，
        // 2 需要请购的 提交请购
        //生成请购单 销售单号按照天 递增
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String today = sdf.format(new Date());
        String codeMaxString = lvDoService.selectMaxCode(today);
        if (StringUtils.isNotBlank(codeMaxString)) {
            // 最大编号+1
            codeMaxString = Long.parseLong(codeMaxString) + 1 + "";
        } else {
            codeMaxString = today + "0001";
        }

        if (!rows.isEmpty()) {
            // lvDo 请购单
            LvDo lvdo = new LvDo();
            lvdo.setMainId(orderIronRecord.getId());
            lvdo.setName(projectBaseInfo.getName());
            lvdo.setCode(projectBaseInfo.getCode());
            lvdo.setSource(BusinessConstants.PLEASE_BUY_SOURCE_MATERIAL);
            lvdo.setNos(codeMaxString);
            lvdo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_MATERIAL_SUBMIT);
            lvdo.setDdDate(projectBaseInfo.getContractDate());
            lvdo.setMoney(projectBaseInfo.getContractMoney());
            lvdo.setSubDate(orderIronRecord.getDeliveryDate());//需求日期
            lvdo.setCustomerId(projectBaseInfo.getCustomId());
            lvdo.setCustomerName(projectBaseInfo.getCustomName());
            lvdo.setUserId(projectBaseInfo.getSalesmanId());
            lvdo.setUserName(projectBaseInfo.getSalesmanName());
            lvdo.setDeptId(projectBaseInfo.getDeptId());
            lvdo.setIsBuy(BusinessConstants.GOODS_IS_BUY_YES);
            lvdo.setDeptName(projectBaseInfo.getDeptName());
            lvDoService.insert(lvdo);

            for (GoodsSaledo entity : rows) {
                goodsSaledo = new GoodsSaledo();
                goodsSaledo.setId(IdUtils.fastSimpleUUID());
//                goodsSaledo.setGongchengName(entity.getGongchengName());
                goodsSaledo.setSaleDate(projectBaseInfo.getDeliveryTime());
                goodsSaledo.setIronRecordId(orderIronRecord.getId());
                goodsSaledo.setType("材料");
                goodsSaledo.setIsdo(entity.getIsdo());
                goodsSaledo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_MATERIAL_SUBMIT);
                goodsSaledo.setGoodsId(entity.getGoodsId());
                goodsSaledo.setGoodsCode(entity.getGoodsCode());
                goodsSaledo.setIsdo(entity.getIsdo());
                goodsSaledo.setGoodModel(entity.getGoodModel());
                goodsSaledo.setGoodsBrand(entity.getGoodsBrand());
                goodsSaledo.setGoodsName(entity.getGoodsName());
                goodsSaledo.setGoodsType(BusinessConstants.GOODS_TYPE_MATERIAL);
                goodsSaledo.setUnit(entity.getUnit());
                goodsSaledo.setGoodsUnitPrice(entity.getGoodsUnitPrice());//销售单价

                goodsSaledo.setPleaseBuyCount(entity.getPleaseBuyCount());
                goodsSaledo.setBuyRemain(entity.getPleaseBuyCount());
                goodsSaledo.setRemark(entity.getRemark());
                goodsSaledo.setProjectId(projectBaseInfo.getId());
                goodsSaledo.setProjectNo(projectBaseInfo.getCode());
                goodsSaledo.setProjectName(projectBaseInfo.getName());
                goodsSaledo.setSalesmanId(projectBaseInfo.getSalesmanId());
                goodsSaledo.setSalesmanName(projectBaseInfo.getSalesmanName());
                goodsSaledo.setCustomerId(projectBaseInfo.getCustomId());
                goodsSaledo.setCustomerName(projectBaseInfo.getCustomName());
                goodsSaledo.setDeptId(projectBaseInfo.getDeptId());
                goodsSaledo.setDeptName(projectBaseInfo.getDeptName());
                goodsSaledo.setDeliveryTime(orderIronRecord.getDeliveryDate());
                goodsSaledo.setMainId(lvdo.getId());
                goodsSaledo.setIsBuy(BusinessConstants.GOODS_IS_BUY_YES);
                goodsSaledo.setNos(lvdo.getNos());
                insert(goodsSaledo);
            }
        }
    }

    @Override
    @Transactional(readOnly = false)
    public int deletSaleInfoForPrj(String id) {
        GoodsSaledo goodsSale = selectById(id);
        GoodsOrderIn goodsOrderIn = goodsOrderInMapper.selectById(goodsSale.getGoodsId());
        if (goodsOrderIn != null) {
            goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().add(goodsSale.getLockCount()));
            goodsOrderIn.setShengyu(goodsOrderIn.getRemainderCount().multiply(goodsOrderIn.getCostPrice()));
            goodsOrderInMapper.update(goodsOrderIn);

            SysArea sysArea = areaService.selectAreaById(goodsOrderIn.getDeptId());
            if (sysArea != null) {
                sysArea.setShengyu(sysArea.getShengyu().add(goodsOrderIn.getRemainderCount()));
                sysArea.setAllmaoney(sysArea.getAllmaoney().add(goodsOrderIn.getShengyu()));
                areaService.updateArea(sysArea);
            }
        }
        //更新项目费用或者销售金额,利润金额信息
        String projectId = goodsSale.getProjectId();
        ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(projectId);

        projectBaseInfo.setFeeMoney(projectBaseInfo.getFeeMoney().subtract(goodsSale.getGoodsTotalPrice()));
        projectBaseInfo.setProfitMoney(projectBaseInfo.getProfitMoney().add(goodsSale.getGoodsBuyTotal()));
        projectBaseInfoService.update(projectBaseInfo);

        return deleteById(id);
    }


    @Override
    public void exportData(HttpServletRequest request, HttpServletResponse response, GoodsSaledo entity) {
        //  List<GoodsSaledo> list = goodsSaledoMapper.selectList(entity);
        List<GoodsSaledo> list = goodsSaledoMapper.listQinggou(entity);
        for (GoodsSaledo goodsSaledo : list) {
            Map<String, Object> params = new HashMap<>();
            params.put("deliveryTime", DateUtils.formatDate(goodsSaledo.getSaleDate(), "yyyy-MM-dd"));
            params.put("orderDate", DateUtils.formatDate(goodsSaledo.getDdDate(), "yyyy-MM-dd"));
            goodsSaledo.setParams(params);
            goodsSaledo.setIsdoDict(DictUtils.getDictLabel("isdo", goodsSaledo.getIsdo()));
            goodsSaledo.setStatus(DictUtils.getDictLabel("goods_status", goodsSaledo.getStatus()));
            goodsSaledo.setSaleStatus(DictUtils.getDictLabel("goods_status", goodsSaledo.getSaleStatus()));
        }
        String fileName = "请购产品列表.xlsx";
        String templateName = "请购产品导出模板.xlsx";
        Map<String, Object> params = new HashMap<>();
        params.put("list", list);
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
    }

    @Override
    public void exportDataByPleaseBuy(HttpServletRequest request, HttpServletResponse response, GoodsSaledo entity) {
        Map<String, Object> params = new HashMap<>();
        LvDo lvDo = lvDoService.selectById(entity.getMainId());
        /*ProjectBaseInfo order = projectBaseInfoService.selectById(lvDo.getMainId());
        Map<String, Object> param = new HashMap<>();*/
        //List<GoodsSaledo> list = goodsSaledoMapper.selectList(entity);
        List<GoodsSaledo> list = goodsSaledoMapper.listQinggou(entity);
        for (GoodsSaledo goodsSaledo : list) {
            params.put("saleDate", DateUtils.formatDate(goodsSaledo.getSaleDate(), "yyyy-MM-dd"));//需求日期
            params.put("orderDate", DateUtils.formatDate(goodsSaledo.getDdDate(), "yyyy-MM-dd"));//下单日期
            goodsSaledo.setIsdoDict(DictUtils.getDictLabel("isdo", goodsSaledo.getIsdo()));
            goodsSaledo.setParams(params);
        }
        String fileName = "订单请购产品列表.xlsx";
        String templateName = "订单请购产品导出模板.xlsx";
        params.put("lvDo", lvDo);
        params.put("list", list);
        //params.put("order", order);
        if (lvDo != null) {
            params.put("ddDate", DateUtils.formatDate(lvDo.getDdDate(), "yyyy-MM-dd"));
        }
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
    }

    @Override
    public void exportByPleaseBuyIds(HttpServletRequest request, HttpServletResponse response, GoodsSaledo entity) {
        List<GoodsSaledo> list = goodsSaledoMapper.selectList(entity);
        for (GoodsSaledo goodsSaledo : list) {
            Map<String, Object> param = new HashMap<>();
            param.put("saleDate", DateUtils.formatDate(goodsSaledo.getSaleDate(), "yyyy-MM-dd"));
            goodsSaledo.setParams(param);
        }
        String fileName = "订单请购产品列表.xlsx";
        String templateName = "多个请购单产品导出模板.xlsx";
        Map<String, Object> params = new HashMap<>();
        params.put("list", list);
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
    }

    //采成品导入
    @Override
    public Map<String, Object> importCaigouData(GoodsSaledo goodsSaledo, MultipartFile file) {
        String tmplName = "goodsSaledoCaigou.xml";
        String errortext = "";
        Map<String, Object> map = new HashMap<>();
        int i = 0;
        int j = 0;
        try {
            InputStream in = new FileInputStream(basePath + File.separator
                    + templatePath + File.separator + templateImport + File.separator + tmplName);
            XLSReader mainReader = ReaderBuilder.buildFromXML(in);
            List<GoodsSaledo> list = new ArrayList<>();
            List<GoodsSaledo> listCaigou = new ArrayList<>();
            Map beans = new HashMap();
            beans.put("list", list);
            XLSReadStatus readStatus = mainReader.read(file.getInputStream(), beans);
            if (readStatus.isStatusOK()) {
                for (int k = 0; k < list.size(); k++) {
                    GoodsSaledo entity = new GoodsSaledo();
                    entity.setId(IdUtils.fastSimpleUUID());
                    GoodsSaledo info = list.get(k);
                    BeanUtils.copyProperties(info, entity, "id");
                    try {
                        if (StringUtils.isNotBlank(info.getIdx())) {
                            entity.setIdx(info.getIdx());
                        }
                    } catch (Exception e) {
                        errortext += "序号为" + info.getIdx() + "行数据，序号应为数字，请修改后导入！";
                        break;
                    }
                    //请购单号和请购单
                    if (StringUtils.isNotBlank(info.getNos())) {
                        List<LvDo> lvDoList = lvDoService.selectByNos(info.getNos());
                        if (lvDoList.size() == 0) {
                            LvDo lvdo = new LvDo();
                            lvdo.setNos(info.getNos());
                            lvdo.setSource(BusinessConstants.SOURCE_9);//u8
                            lvdo.setStatus(BusinessConstants.PROJECT_6);//采购同意
                            lvdo.setIsdo(BusinessConstants.GOODS_DO_NO);//不自制
                            lvdo.setDdDate(new Date());
                            lvdo.setType("9");//采购类型
                            lvdo.setYwType("1");//业务类型
                            lvDoService.insert(lvdo);
                            entity.setMainId(lvdo.getId());
                        } else if (lvDoList.size() == 1) {
                            if (StringUtils.isNotBlank(info.getGoodsCode())) {
                                 /*List<GoodsSaledo> goodsSaledo1 = goodsSaledoMapper.listByMainIdAandCode(lvDoList.get(0).getId(), info.getGoodsCode());
                                 if (goodsSaledo1.size() > 0) {
                                     errortext += "序号为" + info.getIdx() + "行数据，请购单已导入过该产品，请确认后导入！";
                                     break;
                                 }*/
                                entity.setMainId(lvDoList.get(0).getId());
                            } else {
                                errortext += "序号为" + info.getIdx() + "行数据，存货编码是空数据，请修改后重新导入！";
                            }
                        } else {
                            errortext += "序号为" + info.getIdx() + "行数据，请购单号出现多次，请修改后导入！";
                            break;
                        }
                    } else {
                        errortext += "序号为" + info.getIdx() + "行数据，请购单号不能为空，请修改后导入！";
                        break;
                    }
                    //请购日期
                    try {
                        if (StringUtils.isNotBlank(info.getCreateTimeStr())) {
                            boolean arriveTimeMatch = Pattern.matches("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}", info.getCreateTimeStr());
                            if (!arriveTimeMatch) {
                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                entity.setCreateTime(df.parse(info.getCreateTimeStr()));
                            } else {
                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                String date = df.format(DateUtil.getJavaDate(Double.parseDouble(info.getCreateTimeStr())));
                                entity.setCreateTime(DateUtils.parseDate(date, "yyyy-MM-dd"));
                            }
                        }
                    } catch (Exception e) {
                        errortext += "行号为 " + info.getIdx() + "行的数据，日期时间格式错误，请修改后再上传！";
                        break;
                    }
                    //业务员

                    //产品编码
                    if (StringUtils.isBlank(info.getGoodsCode())) {
                        errortext += "序号为" + info.getIdx() + "行数据，存货编码是空数据，请修改后重新导入！";
                    } else {
                        GoodsOrderIn goods = goodsOrderInMapper.selectByCode(info.getGoodsCode());
                        if (goods != null) {
                            entity.setGoodsId(goods.getId());
                            entity.setGoodsCode(goods.getCode());
                            entity.setGoodsName(goods.getName());
                            entity.setGoodModel(goods.getModel());
                            entity.setGoodsType(goods.getGoodsType());
                        } else {
                            errortext += "序号为" + info.getIdx() + "行数据，存货编码为:" + info.getGoodsCode() + "，不存在库存内，请检查后导入！";
                        }
                    }
                    //请购数量
                    try {
                        if (StringUtils.isNotBlank(info.getOrderCountStr())) {
                            entity.setOrderCount(new BigDecimal(info.getOrderCountStr()));
                            entity.setPleaseBuyCount(new BigDecimal(info.getOrderCountStr()));
                        }
                    } catch (Exception e) {
                        errortext += "行号为 " + info.getIdx() + "行的数据，请购数量格式错误，请修改后再上传！";
                        break;
                    }
                    //需求日期
                    try {
                        if (StringUtils.isNotBlank(info.getSaleDateStr())) {
                            boolean arriveTimeMatch = Pattern.matches("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}", info.getSaleDateStr());
                            if (!arriveTimeMatch) {
                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                entity.setSaleDate(df.parse(info.getSaleDateStr()));
                            } else {
                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                String date = df.format(DateUtil.getJavaDate(Double.parseDouble(info.getSaleDateStr())));
                                entity.setSaleDate(DateUtils.parseDate(date, "yyyy-MM-dd"));
                            }
                        }
                    } catch (Exception e) {
                        errortext += "行号为 " + info.getIdx() + "行的数据，需求日期格式错误，请修改后再上传！";
                        break;
                    }
                    //中标价（销售订单价）
                    try {
                        if (StringUtils.isNotBlank(info.getGoodsUnitPriceStr())) {
                            entity.setGoodsUnitPrice(new BigDecimal(info.getGoodsUnitPriceStr()));
                            entity.setGoodsTotalPrice(new BigDecimal(info.getGoodsUnitPriceStr()).multiply(new BigDecimal(info.getOrderCountStr())));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errortext += "行号为 " + info.getIdx() + "行的数据，中标价格式错误，请修改后再上传！";
                        break;
                    }
                    //采购价
                    try {
                        if (StringUtils.isNotBlank(info.getGoodsBuyPriceStr())) {
                            entity.setGoodsBuyPrice(new BigDecimal(info.getGoodsBuyPriceStr()));
                            entity.setGoodsBuyTotal(new BigDecimal(info.getGoodsBuyPriceStr()).multiply(new BigDecimal(info.getOrderCountStr())));
                        }
                    } catch (Exception e) {
                        errortext += "行号为 " + info.getIdx() + "行的数据，采购价格式错误，请修改后再上传！";
                        break;
                    }
                    try {
                        if (StringUtils.isNotBlank(info.getSupplierName())) {
                            GoodsSupplier goodsSupplier = iGoodsSupplierService.selectByName(info.getSupplierName());
                            if (goodsSupplier != null) {
                                entity.setSupplierId(goodsSupplier.getId());
                                entity.setSupplierName(goodsSupplier.getName());
                            } else {
                                errortext += "行号为 " + info.getIdx() + "行的数据，供应商在供应商库中不存在，请添加后再上传！";
                                break;
                            }
                        } else {
                            errortext += "行号为 " + info.getIdx() + "行的数据，供应商未填写，请填写后再上传！";
                            break;
                        }
                    } catch (Exception e) {
                        errortext += "行号为 " + info.getIdx() + "行的数据，供应商在供应商库中多次存在，请删除其中一个后再上传！";
                        break;
                    }
                    entity.setType("u8导入");
                    entity.setDeptId("e81c16ccf8924344bf9215bfb1643d7b");
                    entity.setDeptName("业务部");
                    entity.setStatus(BusinessConstants.SALE_TYPE_13);//采购同意
                    entity.setIsBuy("1");
                    entity.setIsdo(BusinessConstants.GOODS_DO_NO);
                    entity.setBuyRemain(entity.getPleaseBuyCount());
                    if (StringUtils.isNotBlank(errortext)) {
                        map.put("errorText", errortext);
                        map.put("num", i);
                        map.put("numupdate", j);
                        return map;
                    } else {
                        listCaigou.add(entity);
                    }
                }
            }
            if (StringUtils.isBlank(errortext)) {
                for (GoodsSaledo info : listCaigou) {
                    i += this.insert(info);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("errorText", errortext);
        map.put("num", i);
        map.put("numupdate", j);
        return map;
    }

    //采购材料导入
    @Override
    public Map<String, Object> importCaigouCailiao(GoodsSaledo goodsSaledo, MultipartFile file) {
        String tmplName = "goodsSaledoCaigouCailiao.xml";
        String errortext = "";
        Map<String, Object> map = new HashMap<>();
        int i = 0;
        int j = 0;
        try {
            InputStream in = new FileInputStream(basePath + File.separator
                    + templatePath + File.separator + templateImport + File.separator + tmplName);
            XLSReader mainReader = ReaderBuilder.buildFromXML(in);
            List<GoodsSaledo> list = new ArrayList<>();
            List<GoodsSaledo> listCaigou = new ArrayList<>();
            Map beans = new HashMap();
            beans.put("list", list);
            XLSReadStatus readStatus = mainReader.read(file.getInputStream(), beans);
            if (readStatus.isStatusOK()) {
                for (int k = 0; k < list.size(); k++) {
                    GoodsSaledo entity = new GoodsSaledo();
                    entity.setId(IdUtils.fastSimpleUUID());
                    GoodsSaledo info = list.get(k);
                    BeanUtils.copyProperties(info, entity, "id");
                    try {
                        if (StringUtils.isNotBlank(info.getIdx())) {
                            entity.setIdx(info.getIdx());
                        }
                    } catch (Exception e) {
                        errortext += "序号为" + info.getIdx() + "行数据，序号应为数字，请修改后导入！";
                        break;
                    }
                    //请购单号和请购单
                    if (StringUtils.isNotBlank(info.getNos())) {
                        List<LvDo> lvDoList = lvDoService.selectByNos(info.getNos());
                        if (lvDoList.size() == 0) {
                            LvDo lvdo = new LvDo();
                            lvdo.setNos(info.getNos());
                            lvdo.setSource(BusinessConstants.SOURCE_9);//u8
                            lvdo.setStatus(BusinessConstants.PROJECT_6);//采购同意
                            lvdo.setIsdo(BusinessConstants.GOODS_DO_NO);//不自制
                            lvdo.setDdDate(new Date());
                            lvdo.setType("9");//采购类型
                            lvdo.setYwType("1");//业务类型
                            lvDoService.insert(lvdo);
                            entity.setMainId(lvdo.getId());
                        } else if (lvDoList.size() == 1) {
                            if (StringUtils.isNotBlank(info.getGoodsCode())) {
                               /* List<GoodsSaledo> goodsSaledo1 = goodsSaledoMapper.listByMainIdAandCode(lvDoList.get(0).getId(), info.getGoodsCode());
                                if (goodsSaledo1.size() > 0) {
                                    errortext += "序号为" + info.getIdx() + "行数据，请购单已导入过改产品，请确认后导入！";
                                    break;
                                }*/
                                entity.setMainId(lvDoList.get(0).getId());
                            } else {
                                errortext += "序号为" + info.getIdx() + "行数据，存货编码是空数据，请修改后重新导入！";
                            }
                        } else {
                            errortext += "序号为" + info.getIdx() + "行数据，请购单号出现多次，请修改后导入！";
                            break;
                        }
                    } else {
                        errortext += "序号为" + info.getIdx() + "行数据，请购单号不能为空，请修改后导入！";
                        break;
                    }
                    //请购日期
                    try {
                        if (StringUtils.isNotBlank(info.getCreateTimeStr())) {
                            boolean arriveTimeMatch = Pattern.matches("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}", info.getCreateTimeStr());
                            if (!arriveTimeMatch) {
                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                entity.setCreateTime(df.parse(info.getCreateTimeStr()));
                            } else {
                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                String date = df.format(DateUtil.getJavaDate(Double.parseDouble(info.getCreateTimeStr())));
                                entity.setCreateTime(DateUtils.parseDate(date, "yyyy-MM-dd"));
                            }
                        }
                    } catch (Exception e) {
                        errortext += "行号为 " + info.getIdx() + "行的数据，日期时间格式错误，请修改后再上传！";
                        break;
                    }
                    //业务员

                    //产品编码
                    if (StringUtils.isBlank(info.getGoodsCode())) {
                        errortext += "序号为" + info.getIdx() + "行数据，存货编码是空数据，请修改后重新导入！";
                    } else {
                        GoodsOrderIn goods = goodsOrderInMapper.selectByCode(info.getGoodsCode());
                        if (goods != null) {
                            entity.setGoodsId(goods.getId());
                            entity.setGoodsCode(goods.getCode());
                            entity.setGoodsName(goods.getName());
                            entity.setGoodModel(goods.getModel());
                            entity.setGoodsType(goods.getGoodsType());
                        } else {
                            errortext += "序号为" + info.getIdx() + "行数据，存货编码为:" + info.getGoodsCode() + "，不存在库存内，请检查后导入！";
                        }
                    }

                    //吨位
                    try {
                        if (StringUtils.isNotBlank(info.getDunStr())) {
                            entity.setDun(new BigDecimal(info.getDunStr()));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errortext += "行号为 " + info.getIdx() + "行的数据，重量格式错误，请修改后再上传！";
                        break;
                    }
                    //请购数量
                    try {
                        if (StringUtils.isNotBlank(info.getOrderCountStr())) {
                            entity.setOrderCount(new BigDecimal(info.getOrderCountStr()));
                            entity.setPleaseBuyCount(new BigDecimal(info.getOrderCountStr()));
                            entity.setBuyRemain(new BigDecimal(info.getOrderCountStr()));
                        }
                    } catch (Exception e) {
                        errortext += "行号为 " + info.getIdx() + "行的数据，请购数量格式错误，请修改后再上传！";
                        break;
                    }
                    //需求日期
                    try {
                        if (StringUtils.isNotBlank(info.getSaleDateStr())) {
                            boolean arriveTimeMatch = Pattern.matches("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}", info.getSaleDateStr());
                            if (!arriveTimeMatch) {
                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                entity.setSaleDate(df.parse(info.getSaleDateStr()));
                            } else {
                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                String date = df.format(DateUtil.getJavaDate(Double.parseDouble(info.getSaleDateStr())));
                                entity.setSaleDate(DateUtils.parseDate(date, "yyyy-MM-dd"));
                            }
                        }
                    } catch (Exception e) {
                        errortext += "行号为 " + info.getIdx() + "行的数据，需求日期格式错误，请修改后再上传！";
                        break;
                    }
                    //中标价（销售订单价）
                    try {
                        if (StringUtils.isNotBlank(info.getGoodsUnitPriceStr())) {
                            entity.setGoodsUnitPrice(new BigDecimal(info.getGoodsUnitPriceStr()));
                            if (StringUtils.isNotBlank(info.getDunStr())) {
                                entity.setGoodsTotalPrice(new BigDecimal(info.getGoodsUnitPriceStr()).multiply(new BigDecimal(info.getDunStr())));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errortext += "行号为 " + info.getIdx() + "行的数据，中标价格式错误，请修改后再上传！";
                        break;
                    }
                    //采购价
                    try {
                        if (StringUtils.isNotBlank(info.getGoodsBuyPriceStr())) {
                            entity.setGoodsBuyPrice(new BigDecimal(info.getGoodsBuyPriceStr()));
                            if (StringUtils.isNotBlank(info.getDunStr())) {
                                entity.setGoodsBuyTotal(new BigDecimal(info.getGoodsBuyPriceStr()).multiply(new BigDecimal(info.getDunStr())));
                            }
                        } else {
                            errortext += "行号为 " + info.getIdx() + "行的数据，采购价格未填写，请填写后后再上传！";
                            break;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errortext += "行号为 " + info.getIdx() + "行的数据，采购价格式错误，请修改后再上传！";
                        break;
                    }
                    try {
                        if (StringUtils.isNotBlank(info.getGoodsBuyTotalStr())) {
                            entity.setGoodsBuyTotal(new BigDecimal(info.getGoodsBuyTotalStr()));
                        } else {
                            if (StringUtils.isNotBlank(info.getDunStr())) {
                                entity.setGoodsBuyTotal(new BigDecimal(info.getGoodsBuyPriceStr()).multiply(new BigDecimal(info.getDunStr())));
                            } else {
                                if (StringUtils.isNotBlank(info.getOrderCountStr())) {
                                    entity.setGoodsBuyTotal(new BigDecimal(info.getGoodsBuyPriceStr()).multiply(new BigDecimal(info.getOrderCountStr())));
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errortext += "行号为 " + info.getIdx() + "行的数据，采购总金额格式错误，请修改后再上传！";
                        break;
                    }
                    try {
                        if (StringUtils.isNotBlank(info.getSupplierName())) {
                            GoodsSupplier goodsSupplier = iGoodsSupplierService.selectByName(info.getSupplierName());
                            if (goodsSupplier != null) {
                                entity.setSupplierId(goodsSupplier.getId());
                                entity.setSupplierName(goodsSupplier.getName());
                            } else {
                                errortext += "行号为 " + info.getIdx() + "行的数据，供应商在供应商库中不存在，请添加后再上传！";
                                break;
                            }
                        } else {
                            errortext += "行号为 " + info.getIdx() + "行的数据，供应商未填写，请填写后再上传！";
                            break;
                        }
                    } catch (Exception e) {
                        errortext += "行号为 " + info.getIdx() + "行的数据，供应商在供应商库中多次存在，请删除其中一个后再上传！";
                        break;
                    }
                    entity.setType("u8导入");
                    entity.setDeptId("e81c16ccf8924344bf9215bfb1643d7b");
                    entity.setDeptName("业务部");
                    entity.setStatus(BusinessConstants.SALE_TYPE_13);//采购同意
                    entity.setIsBuy("1");
                    //entity.setBuyRemain(entity.getPleaseBuyCount());
                    entity.setIsdo(BusinessConstants.GOODS_DO_NO);
                    if (StringUtils.isNotBlank(errortext)) {
                        map.put("errorText", errortext);
                        map.put("num", i);
                        map.put("numupdate", j);
                        return map;
                    } else {
                        listCaigou.add(entity);
                    }
                }
            }
            if (StringUtils.isBlank(errortext)) {
                for (GoodsSaledo info : listCaigou) {
                    i += this.insert(info);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("errorText", errortext);
        map.put("num", i);
        map.put("numupdate", j);
        return map;
    }

    // 铁件请购
    @Override
    public void insertBatchIron(LvDo lvDo) {
        List<GoodsSaledo> rows = lvDo.getGoodsSaledoList();
        ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo();
        if (StringUtils.isNotBlank(lvDo.getMainId())) {
            projectBaseInfo = projectBaseInfoService.selectById(lvDo.getMainId());
        }
        LvDo lvdo = new LvDo();
        if (StringUtils.isNotBlank(projectBaseInfo.getId())) {
            lvdo.setCode(projectBaseInfo.getCode());
            lvdo.setName(projectBaseInfo.getName());
            lvdo.setMainId(projectBaseInfo.getId());
        }
        lvdo.setSource(BusinessConstants.PLEASE_BUY_SOURCE_IRON);
        lvdo.setIronStatus(BusinessConstants.PLEASE_BUY_IRON_STATUS_TECH_SUBMIT);
        lvdo.setDdDate(lvDo.getDdDate());
        lvdo.setSubDate(lvDo.getSubDate());
        lvdo.setCustomerId(lvDo.getCustomerId());
        lvdo.setCustomerName(lvDo.getCustomerName());
        lvdo.setUserId(lvDo.getUserId());
        lvdo.setUserName(lvDo.getUserName());
        lvdo.setDeptId(lvDo.getDeptId());
        lvdo.setDeptName(lvDo.getDeptName());
        lvdo.setYwType(lvDo.getYwType());
        lvdo.setType(lvDo.getType());
        lvdo.setRemark(lvDo.getRemark());
        lvDoService.insert(lvdo);
        if (!rows.isEmpty()) {
            for (GoodsSaledo goodsSaledo : rows) {
                if (goodsSaledo != null) {
                    goodsSaledo.setProjectId(lvdo.getMainId());
                    goodsSaledo.setProjectNo(lvdo.getCode());
                    goodsSaledo.setProjectName(lvdo.getName());
                    goodsSaledo.setSalesmanId(lvdo.getUserId());
                    goodsSaledo.setSalesmanName(lvdo.getUserName());
                    goodsSaledo.setCustomerId(lvdo.getCustomerId());
                    goodsSaledo.setCustomerName(lvdo.getCustomerName());
                    goodsSaledo.setDeptId(lvdo.getDeptId());
                    goodsSaledo.setDeptName(lvdo.getDeptName());
                    goodsSaledo.setMainId(lvdo.getId());
                    goodsSaledo.setSaleDate(lvdo.getSubDate());
                    goodsSaledo.setNos(lvdo.getNos());
                    goodsSaledo.setType("其他");
                    goodsSaledo.setIsBuy("1");
                    goodsSaledo.setPleaseBuyCount(goodsSaledo.getPleaseBuyApplyCount());
                    goodsSaledo.setBuyRemain(goodsSaledo.getPleaseBuyApplyCount());
                    goodsSaledo.setStatus(BusinessConstants.PROJECT_3);
                    if (StringUtils.isBlank(goodsSaledo.getGoodsId())) {
                        continue;
                    }
                    if (StringUtils.isNotBlank(goodsSaledo.getId())) {
                        update(goodsSaledo);
                    } else {
                        insert(goodsSaledo);
                    }
                }
            }
        }
    }


    // 铁件请购
    @Override
    public void updateBatchIron(LvDo lvDo) {
        List<GoodsSaledo> rows = lvDo.getGoodsSaledoList();
        lvDoService.update(lvDo);
        // 先删除下面的产品
        deleteBuyLvDoId(lvDo.getId());
        for (GoodsSaledo goodsSaledo : rows) {
            if (goodsSaledo != null) {
                goodsSaledo.setSalesmanId(lvDo.getUserId());
                goodsSaledo.setSalesmanName(lvDo.getUserName());
                goodsSaledo.setCustomerId(lvDo.getCustomerId());
                goodsSaledo.setCustomerName(lvDo.getCustomerName());
                goodsSaledo.setDeptId(lvDo.getDeptId());
                goodsSaledo.setDeptName(lvDo.getDeptName());
                goodsSaledo.setMainId(lvDo.getId());
                goodsSaledo.setSaleDate(lvDo.getSubDate());
                goodsSaledo.setNos(lvDo.getNos());
                goodsSaledo.setType("其他");
                goodsSaledo.setIsBuy("1");
                goodsSaledo.setPleaseBuyCount(goodsSaledo.getPleaseBuyApplyCount());
                goodsSaledo.setStatus(BusinessConstants.PROJECT_3);
                if (StringUtils.isBlank(goodsSaledo.getGoodsId())) {
                    continue;
                }
                insert(goodsSaledo);
            }
        }
    }

    public void deleteBuyLvDoId(String mainId){
        goodsSaledoMapper.deleteBuyLvDoId(mainId);
    };

    @Override
    public List<GoodsSaledo> listGoods(GoodsSaledo entity) {
        return goodsSaledoMapper.listGoods(entity);
    }

    @Override
    public List<GoodsSaledo> selectBySaleId(String goodsSaleId) {
        return goodsSaledoMapper.selectBySaleId(goodsSaleId);
    }

    //铁件产品请购添加
    @Override
    public void insertPleaseBuyForIron(GoodsSaledo goodsSaledo) {
        List<GoodsOrderIn> rows = goodsSaledo.getColumnsDo();
        if (!rows.isEmpty()) {
            for (GoodsOrderIn entity : rows) {
                goodsSaledo = new GoodsSaledo();
                goodsSaledo.setId(IdUtils.fastSimpleUUID());
                goodsSaledo.setType("其他");
                goodsSaledo.setIsBuy("1");
                goodsSaledo.setStatus(BusinessConstants.PROJECT_2);//请购中
                goodsSaledo.setGoodsId(entity.getId());
                goodsSaledo.setGoodsCode(entity.getCode());
                goodsSaledo.setGoodModel(entity.getModel());
                goodsSaledo.setGoodsBrand(entity.getBrand());
                goodsSaledo.setGoodsName(entity.getName());
                goodsSaledo.setUnit(entity.getUnit());
                goodsSaledo.setGoodsType(entity.getGoodsType());
                goodsSaledo.setPleaseBuyApplyCount(entity.getCounts());
                goodsSaledo.setOrderCount(entity.getCounts());//订单需求量
                goodsSaledo.setPleaseBuyCount(entity.getCounts());//请购数量
                goodsSaledo.setBuyRemain(entity.getCounts());//剩余采购数量
                goodsSaledo.setRemark(entity.getRemark());
                insert(goodsSaledo);
            }
        }

    }


    //更新铁件 驳回的产品提交请购
    @Override
    @Transactional
    public void updateLvdoIron(LvDo lvDo) {
        List<GoodsOrderIn> rows = lvDo.getColumns();
        ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo();
        if (StringUtils.isNotBlank(lvDo.getMainId())) {
            projectBaseInfo = projectBaseInfoService.selectById(lvDo.getMainId());
        }
        lvDo.setNos(lvDo.getNos());
        if (StringUtils.isNotBlank(projectBaseInfo.getId())) {
            lvDo.setCode(projectBaseInfo.getCode());
            lvDo.setName(projectBaseInfo.getName());
            lvDo.setMainId(projectBaseInfo.getId());
        } else {
            lvDo.setCode("");
            lvDo.setName("");
            lvDo.setMainId("");
        }
        lvDo.setIronStatus(BusinessConstants.PLEASE_BUY_IRON_STATUS_TECH_SUBMIT);
        lvDo.setDdDate(lvDo.getDdDate());//下单日期
        lvDo.setSubDate(lvDo.getSubDate());//需求日期
        lvDo.setCustomerId(lvDo.getCustomerId());
        lvDo.setCustomerName(lvDo.getCustomerName());
        lvDo.setUserId(lvDo.getUserId());
        lvDo.setUserName(lvDo.getUserName());
        lvDo.setDeptId(lvDo.getDeptId());
        lvDo.setDeptName(lvDo.getDeptName());
        lvDo.setYwType(lvDo.getYwType());
        lvDo.setType(lvDo.getType());
        lvDo.setRemark(lvDo.getRemark());
        lvDoService.update(lvDo);
        if (!rows.isEmpty()) {
            for (GoodsOrderIn entity : rows) {
                GoodsSaledo goodsSaledo = goodsSaledoMapper.selectById(entity.getId());
                if (goodsSaledo != null) {
                    goodsSaledo.setProjectId(lvDo.getMainId());
                    goodsSaledo.setProjectNo(lvDo.getCode());
                    goodsSaledo.setProjectName(lvDo.getName());
                    goodsSaledo.setSalesmanId(lvDo.getUserId());
                    goodsSaledo.setSalesmanName(lvDo.getUserName());
                    goodsSaledo.setCustomerId(lvDo.getCustomerId());
                    goodsSaledo.setCustomerName(lvDo.getCustomerName());
                    goodsSaledo.setDeptId(lvDo.getDeptId());
                    goodsSaledo.setDeptName(lvDo.getDeptName());
                    goodsSaledo.setMainId(lvDo.getId());
                    goodsSaledo.setNos(lvDo.getNos());
                    goodsSaledo.setSaleDate(lvDo.getSubDate());//需求日期
                    if (BusinessConstants.GOODS_DO_YES.equals(goodsSaledo.getIsdo())) {
                        goodsSaledo.setStatus(BusinessConstants.GOODS_STATUS_IS_DO_YES);
                    } else {
                        goodsSaledo.setStatus(BusinessConstants.GOODS_3);
                    }
                    update(goodsSaledo);
                }
            }
        }
    }


    @Override
    public void pleaseBuyForTwiceToTech(LvDo lvDo) {
        //   申请请购产品数量
        List<GoodsSaledo> rows = lvDo.getGoodsSaledoList();
        //生成请购单 销售单号按照天 递增
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String today = sdf.format(new Date());
        String codeMaxString = lvDoService.selectMaxCode(today);
        if (StringUtils.isNotBlank(codeMaxString)) {
            // 最大编号+1
            codeMaxString = Long.parseLong(codeMaxString) + 1 + "";
        } else {
            codeMaxString = today + "0001";
        }
        if (!rows.isEmpty()) {
            // lvDo 请购单
            lvDo.setSource(BusinessConstants.PLEASE_BUY_SOURCE_ORDER_TWICE);
            lvDo.setNos(codeMaxString);
            lvDo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_STORE_SUBMIT);
            StringBuilder orderCodes = new StringBuilder();
            StringBuilder orderIds = new StringBuilder();
            for (GoodsSaledo entity : rows) {
                orderCodes.append(entity.getProjectNo()).append(",");
                orderIds.append(entity.getProjectId()).append(",");
            }
            lvDo.setMainId(orderIds.toString());
            lvDo.setCode(orderCodes.toString());
            lvDoService.insert(lvDo);

            for (GoodsSaledo entity : rows) {
                entity.setMainId(lvDo.getId());
                entity.setStatus("22");
                update(entity);
            }
        }
    }

    @Override
    public void pleaseBuyForTwiceToBuy(LvDo lvDo) {
        //   申请请购产品数量
        List<GoodsSaledo> rows = lvDo.getGoodsSaledoList();
        //生成请购单 销售单号按照天 递增
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String today = sdf.format(new Date());
        String codeMaxString = lvDoService.selectMaxCode(today);
        if (StringUtils.isNotBlank(codeMaxString)) {
            // 最大编号+1
            codeMaxString = Long.parseLong(codeMaxString) + 1 + "";
        } else {
            codeMaxString = today + "0001";
        }
        if (!rows.isEmpty()) {
            // lvDo 请购单
            lvDo.setSource(BusinessConstants.PLEASE_BUY_SOURCE_ORDER_TWICE);
            lvDo.setNos(codeMaxString);
            lvDo.setStatus(BusinessConstants.PLEASE_BUY_STATUS_TECH_SUBMIT);
            StringBuilder orderCodes = new StringBuilder();
            StringBuilder orderIds = new StringBuilder();
            for (GoodsSaledo entity : rows) {
                orderCodes.append(entity.getProjectNo()).append(",");
                orderIds.append(entity.getProjectId()).append(",");
            }
            lvDo.setMainId(orderIds.toString());
            lvDo.setCode(orderCodes.toString());
            lvDoService.insert(lvDo);
            for (GoodsSaledo entity : rows) {
                entity.setMainId(lvDo.getId());
                entity.setStatus("22");
                entity.setNos(codeMaxString);
                update(entity);
            }
        }
    }
}
